Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,15 @@ enum PGM_ErrorCode {
PGM_regular_error = 1, /**< some error occurred which is not in the batch calculation */
PGM_batch_error = 2, /**< some error occurred which is in the batch calculation */
PGM_serialization_error = 3, /**< some error occurred which is in the (de)serialization process */
PGM_dataset_error = 4, /**< Error occurs during dataset handling. */
PGM_data_error = 5, /**< There was a problem with the contents of the provided data. */
PGM_calculation_error = 6, /**< Error occurs during the actual calculation. */
PGM_illegal_operation =
7, /**< An illegal operation was attempted to the C API, such as accessing a null pointer. */
PGM_bad_request = 8, /**< A bad request was attempted to the C API, such as providing the wrong dataset type. */
PGM_not_implemented = 9, /**< The functionality is either not supported or not yet implemented. */
PGM_internal_error = 10, /**< There was an internal error. */
PGM_unknown_error = 255, /**< An unknown error occurred. */
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ PGM_API void PGM_clear_error(PGM_Handle* handle) PGM_NOEXCEPT;
*/
PGM_API char const* PGM_version(void) PGM_NOEXCEPT;

/**
* @brief Determine whether a PGM_ErrorCode error code represents a subcode of a user-specified error code.
*
* See also #PGM_ErrorCode.
*
* @param handle The pointer to the handle.
* @param error_code The #PGM_ErrorCode error code to be checked.
* @param base_error_code The #PGM_ErrorCode base error code of which the error_code may be a subcode.
* @return 1 if the error_code is a subcode of base_error_code, 0 if it is not.
*/
PGM_API PGM_Idx PGM_error_code_is_subcode_of(PGM_Idx error_code, PGM_Idx base_error_code) PGM_NOEXCEPT;

#ifdef __cplusplus
}
#endif
Expand Down
39 changes: 39 additions & 0 deletions power_grid_model_c/power_grid_model_c/src/handle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@
#include "input_sanitization.hpp"
#include "safe_memory_handling.hpp"

#include <power_grid_model/common/error_codes.hpp>

#include <algorithm>
#include <bit>
#include <iterator>
#include <limits>
#include <type_traits>

namespace {
using namespace power_grid_model;
Expand All @@ -21,6 +26,8 @@ using power_grid_model_c::clear_error;
using power_grid_model_c::compile_time_safe_cast;
using power_grid_model_c::create;
using power_grid_model_c::destroy;
using power_grid_model_c::optional_safe_cast;
using power_grid_model_c::to_c_bool;

constexpr char const* version = PGM_VERSION;
} // namespace
Expand Down Expand Up @@ -66,3 +73,35 @@ char const** PGM_batch_errors(PGM_Handle const* handle) noexcept {
}
void PGM_clear_error(PGM_Handle* handle) noexcept { clear_error(handle); }
char const* PGM_version(void) noexcept { return version; }
namespace {
using underlying_error_code_t = std::underlying_type_t<power_grid_model::PowerGridErrorCode>;

bool is_sub_error_code_of(underlying_error_code_t derived, underlying_error_code_t base) noexcept {
using limits = std::numeric_limits<underlying_error_code_t>;
constexpr auto width =
compile_time_safe_cast<underlying_error_code_t>(power_grid_model::power_grid_error_code_level_width);
constexpr auto max_width =
compile_time_safe_cast<underlying_error_code_t>(power_grid_model::power_grid_error_code_max_width);

static_assert(std::is_unsigned_v<underlying_error_code_t>);
static_assert(limits::digits == max_width);
static_assert(width > 0 && max_width % width == 0); // guarantees the shift below stays within [0, digits)

// the root code (0) only has itself as sub code
if (base == 0u) {
return derived == 0u;
}
// keep as many low levels as base occupies; base != 0 implies n_levels in [1, max_width / width]
auto const n_levels = static_cast<underlying_error_code_t>((std::bit_width(base) + width - 1u) / width);
auto const shift = static_cast<underlying_error_code_t>(max_width - n_levels * width) % max_width;
auto const mask = static_cast<underlying_error_code_t>(limits::max() >> shift);
return (derived & mask) == base;
}
} // namespace

PGM_Idx PGM_error_code_is_subcode_of(PGM_Idx error_code, PGM_Idx base_error_code) noexcept {
auto const safe_error_code = optional_safe_cast<underlying_error_code_t>(error_code);
auto const safe_base_error_code = optional_safe_cast<underlying_error_code_t>(base_error_code);
return to_c_bool<PGM_Idx>(safe_error_code.has_value() && safe_base_error_code.has_value() &&
is_sub_error_code_of(*safe_error_code, *safe_base_error_code));
}
7 changes: 6 additions & 1 deletion power_grid_model_c/power_grid_model_c/src/handle.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

#include <power_grid_model/batch_parameter.hpp>
#include <power_grid_model/common/common.hpp>
#include <power_grid_model/common/exception.hpp>

#include <concepts>
#include <exception>
Expand Down Expand Up @@ -65,6 +66,10 @@
std::exception_ptr const ex_ptr = std::current_exception();
try {
std::rethrow_exception(ex_ptr);
} catch (power_grid_model::PowerGridError const& ex) {
// TODO(mgovers): temporary hack to expose base code in prep of #1635

Check warning on line 70 in power_grid_model_c/power_grid_model_c/src/handle.hpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this "TODO" comment.

See more on https://sonarcloud.io/project/issues?id=PowerGridModel_power-grid-model&issues=AaHVMvi9unFypSXJ3hgE&open=AaHVMvi9unFypSXJ3hgE&pullRequest=1697
auto const base_error_code = std::to_underlying(ex.error_code()) % 256;
handle_regular_error(handle, ex, static_cast<PGM_Idx>(base_error_code), extra_message);
} catch (std::exception const& ex) { // NOSONAR(S1181)
handle_regular_error(handle, ex, error_code, extra_message);
} catch (...) { // NOSONAR(S2738)
Expand All @@ -82,7 +87,7 @@
}

static void handle_unkown_error(PGM_Handle& handle) noexcept {
handle.err_code = PGM_regular_error;
handle.err_code = PGM_unknown_error;
handle.err_msg = "Unknown error!\n";
}
};
Expand Down
34 changes: 19 additions & 15 deletions power_grid_model_c/power_grid_model_c/src/input_sanitization.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,17 @@

#include "power_grid_model_c/basics.h"

#include <exception>
#include <format>
#include <string>
#include <power_grid_model/common/exception.hpp>

#include <cassert>
#include <concepts>
#include <optional>
#include <string_view>
#include <type_traits>
#include <utility>

namespace power_grid_model_c {
class IllegalOperationError : public std::exception {
public:
explicit IllegalOperationError(std::string_view message) : msg_{std::format("Illegal operation: {}\n", message)} {}

char const* what() const noexcept final { return msg_.c_str(); }

private:
std::string msg_;
};
using power_grid_model::IllegalOperationError;

template <typename T, typename U> constexpr T compile_time_safe_cast(U const& value) noexcept {
static_assert(std::convertible_to<U, T>,
Expand All @@ -36,14 +31,23 @@ template <typename T, typename U> constexpr T compile_time_safe_cast(U const& va
}
}

template <std::integral T, std::integral U>
requires std::convertible_to<U, T>
constexpr std::optional<T> optional_safe_cast(U value) noexcept {
if (std::in_range<T>(value)) {
return std::optional<T>{std::in_place, static_cast<T>(value)};
}
return std::nullopt;
}

template <std::integral T, std::integral U>
requires std::convertible_to<U, T>
constexpr auto safe_cast(U value) {
if constexpr (std::same_as<T, U>) {
return value;
} else {
if (std::in_range<T>(value)) {
return static_cast<T>(value);
if (auto const result = optional_safe_cast<T>(value)) {
return *result;
}
throw IllegalOperationError{"Value out of range for target type"};
}
Expand All @@ -62,7 +66,7 @@ template <std::integral T> constexpr PGM_Idx to_c_size(T value) {
}

template <std::integral T> constexpr bool safe_bool(T value) { return value != T{0}; }
template <std::integral T> constexpr T to_c_bool(bool value) { return value ? T{1} : T{0}; }
template <std::integral T> constexpr T to_c_bool(bool value) noexcept { return value ? T{1} : T{0}; }

// safe enum conversion from C integer type to C++ enum type.
//
Expand Down
4 changes: 4 additions & 0 deletions power_grid_model_c/power_grid_model_c/src/model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@
handle_regular_error(handle, ex, PGM_batch_error);
handle.failed_scenarios = ex.failed_scenarios();
handle.batch_errs = ex.err_msgs();
} catch (PowerGridError const& ex) {
// TODO(mgovers): temporary hack to expose base code in prep of #1635

Check warning on line 186 in power_grid_model_c/power_grid_model_c/src/model.cpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this "TODO" comment.

See more on https://sonarcloud.io/project/issues?id=PowerGridModel_power-grid-model&issues=AaHVMvaxunFypSXJ3hgD&open=AaHVMvaxunFypSXJ3hgD&pullRequest=1697
auto const base_error_code = std::to_underlying(ex.error_code()) % 256;
handle_regular_error(handle, ex, static_cast<PGM_Idx>(base_error_code));
} catch (std::exception& ex) { // NOSONAR(S1181)
handle_regular_error(handle, ex, PGM_regular_error);
} catch (...) { // NOSONAR(S2738)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "basics.hpp"

#include "power_grid_model_c/basics.h"
#include "power_grid_model_c/handle.h"
#include "power_grid_model_c/logger.h"

Expand All @@ -29,12 +30,6 @@ class PowerGridError : public std::exception {
std::string message_;
};

class PowerGridRegularError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_regular_error; }
};

class PowerGridSerializationError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Expand All @@ -57,12 +52,60 @@ class PowerGridBatchError : public PowerGridError {
std::vector<FailedScenario> failed_scenarios_;
};

class PowerGridDatasetError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_dataset_error; }
};

class PowerGridDataError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_data_error; }
};

class PowerGridCalculationError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_calculation_error; }
};

class PowerGridIllegalOperationError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_illegal_operation; }
};

class PowerGridBadRequest : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_bad_request; }
};

class PowerGridNotImplementedError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_not_implemented; }
};

class PowerGridInternalError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_internal_error; }
};

class PowerGridUnknownError : public PowerGridError {
public:
using PowerGridError::PowerGridError;
Idx error_code() const noexcept override { return PGM_unknown_error; }
};

class Handle {
public:
Handle() {
if (get() == nullptr) {
throw PowerGridRegularError{"Failed to create handle. This usually points to a severe system issue, such "
"as insufficient or corrupted memory."};
throw PowerGridError{"Failed to create handle. This usually points to a severe system issue, such "
"as insufficient or corrupted memory."};
}
}

Expand All @@ -79,7 +122,7 @@ class Handle {
return;
case PGM_regular_error:
clear_error();
throw PowerGridRegularError{error_message};
throw PowerGridError{error_message};
case PGM_batch_error: {
Idx const n_failed_scenarios = PGM_n_failed_scenarios(handle_ptr);
std::vector<PowerGridBatchError::FailedScenario> failed_scenarios(n_failed_scenarios);
Expand All @@ -96,6 +139,30 @@ class Handle {
case PGM_serialization_error:
clear_error();
throw PowerGridSerializationError{error_message};
case PGM_dataset_error:
clear_error();
throw PowerGridDatasetError{error_message};
case PGM_data_error:
clear_error();
throw PowerGridDataError{error_message};
case PGM_calculation_error:
clear_error();
throw PowerGridCalculationError{error_message};
case PGM_illegal_operation:
clear_error();
throw PowerGridIllegalOperationError{error_message};
case PGM_bad_request:
clear_error();
throw PowerGridBadRequest{error_message};
case PGM_not_implemented:
clear_error();
throw PowerGridNotImplementedError{error_message};
case PGM_internal_error:
clear_error();
throw PowerGridInternalError{error_message};
case PGM_unknown_error:
clear_error();
throw PowerGridUnknownError{error_message};
default:
clear_error();
throw PowerGridError{error_message};
Expand Down
24 changes: 20 additions & 4 deletions src/power_grid_model/_core/error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ class _PgmCErrorCode(IntEnum):
REGULAR_ERROR = 1
BATCH_ERROR = 2
SERIALIZATION_ERROR = 3
DATASET_ERROR = 4
DATA_ERROR = 5
CALCULATION_ERROR = 6
ILLEGAL_OPERATION = 7
BAD_REQUEST = 8
NOT_IMPLEMENTED = 9
INTERNAL_ERROR = 10
UNKNOWN_ERROR = 255


_MISSING_CASE_FOR_ENUM_RE = re.compile(r" is not implemented for (.+) #(-?\d+)!\n")
Expand Down Expand Up @@ -155,10 +163,6 @@ def find_error(batch_size: int = 1, decode_error: bool = True) -> RuntimeError |
match error_code:
case _PgmCErrorCode.NO_ERROR:
return None
case _PgmCErrorCode.REGULAR_ERROR:
error_message = get_pgc().error_message()
error_message += VALIDATOR_MSG
return _interpret_error(error_message, decode_error=decode_error)
case _PgmCErrorCode.BATCH_ERROR:
error_message = "There are errors in the batch calculation." + VALIDATOR_MSG
error = PowerGridBatchError(error_message)
Expand All @@ -173,6 +177,18 @@ def find_error(batch_size: int = 1, decode_error: bool = True) -> RuntimeError |
mask[error.failed_scenarios] = False
error.succeeded_scenarios = all_scenarios[mask]
return error
case _ if error_code in (
_PgmCErrorCode.REGULAR_ERROR,
_PgmCErrorCode.DATASET_ERROR,
_PgmCErrorCode.DATA_ERROR,
_PgmCErrorCode.CALCULATION_ERROR,
_PgmCErrorCode.ILLEGAL_OPERATION,
_PgmCErrorCode.BAD_REQUEST,
_PgmCErrorCode.NOT_IMPLEMENTED,
_PgmCErrorCode.INTERNAL_ERROR,
):
error_message = get_pgc().error_message() + VALIDATOR_MSG
return _interpret_error(error_message, decode_error=decode_error)
case _PgmCErrorCode.SERIALIZATION_ERROR:
return PowerGridSerializationError(get_pgc().error_message())
case _:
Expand Down
10 changes: 5 additions & 5 deletions tests/native_api_tests/test_api_dataset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,27 +177,27 @@ TEST_CASE_TEMPLATE("Native readable dataset - indptr sanitization", DatasetType,
SUBCASE("add_buffer with too low starting point indptr") {
std::vector<Idx> const indptr{-1, 1, 1, 3};
CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr),
PowerGridRegularError, doctest::Contains(indptr_bounds_error_message));
PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message));
}
SUBCASE("add_buffer with too high starting point indptr") {
std::vector<Idx> const indptr{1, 1, 1, 3};
CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr),
PowerGridRegularError, doctest::Contains(indptr_bounds_error_message));
PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message));
}
SUBCASE("add_buffer with too few elements") {
std::vector<Idx> const indptr{0, 1, 1, 3};
CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back() + 1, indptr.data(), nullptr),
PowerGridRegularError, doctest::Contains(indptr_bounds_error_message));
PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message));
}
SUBCASE("add_buffer with too many elements") {
std::vector<Idx> const indptr{0, 1, 1, 3};
CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back() - 1, indptr.data(), nullptr),
PowerGridRegularError, doctest::Contains(indptr_bounds_error_message));
PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message));
}
SUBCASE("add_buffer with non-monotonic indptr") {
std::vector<Idx> const indptr{0, 2, 1, 3};
CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr),
PowerGridRegularError, doctest::Contains(indptr_monotonic_error_message));
PowerGridDatasetError, doctest::Contains(indptr_monotonic_error_message));
}
}

Expand Down
Loading
Loading