Skip to content
Draft
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
28 changes: 28 additions & 0 deletions src/pcms/assert.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#ifndef PCMS_COUPLING_ASSERT_H
#define PCMS_COUPLING_ASSERT_H
#include <cassert>
#include <exception>
#include <string>
#include <sstream>
#include <mpi.h>

// https://stackoverflow.com/questions/16683146/can-macros-be-overloaded-by-number-of-arguments
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions test/test_error_handling.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <catch2/catch_test_macros.hpp>
#include "pcms/assert.h"
#include "pcms/print.h"
#include <iostream>

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);
}