Skip to content

Error: Add std::ostream Operator to Write Error #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions error/include/error/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <fmt/core.h>

#include <exception>
#include <ostream>
#include <string>
#include <utility>

Expand All @@ -20,6 +21,26 @@ struct Error : public std::exception {
*/
Error(const std::string& msg);

/**
* @brief Writes the string representation of an error object to the given
* output stream.
* @param os The output stream.
* @param err The error object.
* @return The output stream.
*
* This operator allows an error object to be printed to the output stream
* using the << operator. The error message will be written to the output
* stream.
*
* @code{.cpp}
* const error::Error err("unknown error");
*
* // Print "error: unknown error"
* std::cout << err << std::endl;
* @endcode
*/
friend std::ostream& operator<<(std::ostream& os, const error::Error& err);

/**
* @brief Returns the explanatory string.
* @return Pointer to a null-terminated string with explanatory information.
Expand Down
4 changes: 4 additions & 0 deletions error/src/error.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ namespace error {

Error::Error(const std::string& msg) : message(msg) {}

std::ostream& operator<<(std::ostream& os, const error::Error& err) {
return os << "error: " << err.what();
}

const char* Error::what() const noexcept { return message.c_str(); }

bool operator==(const Error& lhs, const Error& rhs) {
Expand Down
7 changes: 7 additions & 0 deletions error/test/error_test.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <catch2/catch_test_macros.hpp>
#include <error/error.hpp>
#include <sstream>
#include <string>

TEST_CASE("Error Construction") {
Expand Down Expand Up @@ -43,3 +44,9 @@ TEST_CASE("Error Comparison") {
CHECK_FALSE(err == other_err);
CHECK(err != other_err);
}

TEST_CASE("Error Printing") {
const error::Error err("unknown error");
const auto ss = std::stringstream() << err;
REQUIRE(ss.str() == "error: unknown error");
}