diff --git a/error/include/error/error.hpp b/error/include/error/error.hpp index d06133c..4c7786b 100644 --- a/error/include/error/error.hpp +++ b/error/include/error/error.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -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. diff --git a/error/src/error.cpp b/error/src/error.cpp index 114036c..d064f8e 100644 --- a/error/src/error.cpp +++ b/error/src/error.cpp @@ -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) { diff --git a/error/test/error_test.cpp b/error/test/error_test.cpp index b9dd9db..3663439 100644 --- a/error/test/error_test.cpp +++ b/error/test/error_test.cpp @@ -1,5 +1,6 @@ #include #include +#include #include TEST_CASE("Error Construction") { @@ -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"); +}