diff --git a/src/pcms/assert.h b/src/pcms/assert.h index 8565aec9..70624e67 100644 --- a/src/pcms/assert.h +++ b/src/pcms/assert.h @@ -1,6 +1,9 @@ #ifndef PCMS_COUPLING_ASSERT_H #define PCMS_COUPLING_ASSERT_H #include +#include +#include +#include #include // https://stackoverflow.com/questions/16683146/can-macros-be-overloaded-by-number-of-arguments @@ -44,6 +47,31 @@ namespace pcms { + +class exception : public std::exception +{ +public: + exception(std::string message, int error_code = 0, std::string specific = {}) + : error_code_(error_code) + { + std::ostringstream oss; + oss << message; + if (!specific.empty()) + oss << " | Details: " << specific; + if (error_code_ != 0) + oss << " | Error code: " << error_code_; + error_message_ = oss.str(); + } + + const char* what() const noexcept override { return error_message_.c_str(); } + + int code() const noexcept { return error_code_; } + +private: + std::string error_message_; + int error_code_; +}; + // from scorec/core/pcu_fail.h void Pcms_Assert_Fail(const char* msg) __attribute__((noreturn)); } // namespace pcms diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 4325dab2..d320d70f 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -382,6 +382,7 @@ if(Catch2_FOUND) list( APPEND PCMS_UNIT_TEST_SOURCES + test_error_handling.cpp test_field_transfer.cpp test_uniform_grid.cpp test_omega_h_copy.cpp diff --git a/test/test_error_handling.cpp b/test/test_error_handling.cpp new file mode 100644 index 00000000..d2b9764b --- /dev/null +++ b/test/test_error_handling.cpp @@ -0,0 +1,18 @@ +#include +#include "pcms/assert.h" +#include "pcms/print.h" +#include + +int raise_error(int code) +{ + if (code) { + throw pcms::exception("Test exception", code, "Raising error for testing"); + return 1; + } + return 0; +} + +TEST_CASE("pcms error handling test") +{ + REQUIRE_THROWS_AS(raise_error(1), pcms::exception); +} \ No newline at end of file