Skip to content
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
17 changes: 17 additions & 0 deletions include/errors/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ class Error {
*/
std::string_view message() const;

/**
* @brief Checks whether the object contains an error.
* @return `true` if it contains an error, otherwise `false`.
*
* @code{.cpp}
* const auto err = errors::make("unknown error");
*
* // Print "contains error".
* if (err) {
* std::cout << "contains error" << std::endl;
* } else {
* std::cout << "no error" << std::endl;
* }
* @endcode
*/
explicit operator bool() const;

friend Error make(const std::string& msg);

/**
Expand Down
4 changes: 4 additions & 0 deletions src/error.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ std::string_view Error::message() const {
return *message_ptr;
}

Error::operator bool() const {
return (bool)message_ptr;
}

std::ostream& operator<<(std::ostream& os, const errors::Error& err) {
return os << "error: " << err.message();
}
Expand Down
5 changes: 5 additions & 0 deletions test/error_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ TEST_CASE("Error Construction") {
REQUIRE(err.message() == "unknown error");
}

TEST_CASE("Error Checking") {
const auto err = errors::make("unknown error");
REQUIRE(err);
}

TEST_CASE("Error Printing Using OStream") {
const auto err = errors::make("unknown error");
const auto ss = std::stringstream() << err;
Expand Down