diff --git a/docs/content/result.md b/docs/content/result.md index a1b6af6fa..4c59102cb 100644 --- a/docs/content/result.md +++ b/docs/content/result.md @@ -158,6 +158,10 @@ struct ErrorDetail { // Coarse, format-agnostic category of this failure. rfl::ErrorKind kind = rfl::ErrorKind::other; + // Optional machine-readable rule or error code (e.g. "minimum", + // "size.minimum", "pattern", or a custom validator code). Empty when unset. + std::string code = {}; + bool operator==(const ErrorDetail&) const = default; }; ``` @@ -175,7 +179,7 @@ struct ErrorDetail { - `rfl::ErrorKind::invalid_value` – the wire type was right (or a string-only format token), but domain or lexical conversion failed (for example an out-of-range integer, a negative integer for an unsigned target, an unknown enum or `rfl::Literal` value, an invalid timestamp/Base64/bitset, or an unknown union discriminator). - `rfl::ErrorKind::constraint_violation` – the value parsed to the target C++ type, but violated a declared check such as `rfl::Validator<...>`. -`Error::kind()` returns the error's `rfl::ErrorKind` directly (for multi-error results, it returns the `kind` of the first entry in `.details()`). Note that `ErrorDetail::operator==` compares `kind` in addition to `path` and `message`. +`Error::kind()` returns the error's `rfl::ErrorKind` directly, and `Error::code()` returns its machine-readable rule code (`std::string_view`, empty when unset; for multi-error results, both return the first entry in `.details()`). Built-in validators populate canonical codes (`"equal_to"`, `"not_equal_to"`, `"minimum"`, `"exclusive_minimum"`, `"maximum"`, `"exclusive_maximum"`, `"pattern"`, `"any_of"`, `"one_of"`, `"size"` / `"size.*"`, and `"code_points"` / `"code_points.*"`). Custom validators can attach codes either per-error via `rfl::error(msg, rfl::ErrorKind::constraint_violation, "my_code")` or declaratively via a `static constexpr` `code` member convertible to `std::string_view` (note: any custom validator defining a string-convertible `static` `code` member automatically opts into this). Note that `ErrorDetail::operator==` compares `kind` and `code` in addition to `path` and `message`. Field names are spelled as they appear in the input, that is, after processors such as `rfl::SnakeCaseToCamelCase` or `rfl::SnakeCaseToKebabCase` (which `rfl::cli::read` uses) have been applied. This means the paths line up with the JSON schema generated by `rfl::json::to_schema`. @@ -195,9 +199,11 @@ const auto result = rfl::json::read( for (const auto& detail : result.error().details()) { // First iteration: path = {"files", 1, "inputFile"}, // kind = rfl::ErrorKind::constraint_violation, + // code = "size.minimum", // message = "Size validation failed: ..." // Second iteration: path = {"files", 1, "outputFile"}, // kind = rfl::ErrorKind::missing_field, + // code = "", // message = "Field named 'outputFile' not found." } ``` @@ -206,11 +212,13 @@ An error that does not belong to any particular field, such as a syntax error in ## `rfl::error` -`rfl::error("error message")` is a simple utility function for `rfl::Unexpected(Error("error message"))`. You can also pass an `rfl::ErrorKind` (and optionally a `std::vector` path): +`rfl::error("error message")` is a simple utility function for `rfl::Unexpected(Error("error message"))`. You can also pass an `rfl::ErrorKind`, an optional `std::vector` path, and an optional machine-readable code: ```cpp rfl::error("Port out of range", rfl::ErrorKind::invalid_value); rfl::error("Port out of range", rfl::ErrorKind::invalid_value, {"port"}); +rfl::error("Must be even", rfl::ErrorKind::constraint_violation, "even"); +rfl::error("Must be even", rfl::ErrorKind::constraint_violation, {"port"}, "even"); ``` ## `.or_else(...)`, `.transform_error(...)` diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index 5b61bb2bf..ed6e823d8 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -5,6 +5,7 @@ #include #include "Result.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -33,13 +34,16 @@ struct AllOf { private: template static rfl::Result validate_impl(T _value) noexcept { + auto res = Head::validate(std::move(_value)); + if (!res) { + auto err = std::move(res).error(); + internal::set_error_kind_if_other(err, ErrorKind::constraint_violation); + internal::set_error_code_if_empty(err, internal::validator_code()); + return error(std::move(err)); + } if constexpr (sizeof...(Tail) == 0) { - return Head::validate(std::move(_value)); + return res; } else { - auto res = Head::validate(std::move(_value)); - if (!res) { - return res; - } return validate_impl(std::move(*res)); } } diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index eb6425401..90faacecf 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -52,7 +52,9 @@ struct AnyOf { const auto handle_err = [&](Error&& _err) -> rfl::Result { _errors.push_back(std::forward(_err)); if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); + return error(Error(make_error_message(_errors), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::any_of)); } else { return validate_impl( _value, std::forward>(_errors)); diff --git a/include/rfl/CodePoints.hpp b/include/rfl/CodePoints.hpp index edbadb986..093c8a72a 100644 --- a/include/rfl/CodePoints.hpp +++ b/include/rfl/CodePoints.hpp @@ -7,6 +7,7 @@ #include "Result.hpp" #include "Size.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -41,8 +42,11 @@ struct CodePoints { } auto res = V::validate(n); if (!res) { - return error("Code point count validation failed: " + - res.error().what()); + return error(internal::compose_prefixed_validator_error( + std::move(res).error(), + "Code point count validation failed: ", "code_points.", + internal::BuiltinErrorCode::code_points, + internal::compose_code_points_code)); } return std::move(_t); } diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 8b302cf13..2890dd9ef 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -52,27 +52,20 @@ struct OneOf { template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - return Head::validate(_value) - .and_then([&](auto&&) -> rfl::Result { - if constexpr (sizeof...(Tail) == 0) { - if (_errors.size() == sizeof...(Cs)) { - return _value; - // The AI suggests return std::forward(_result); - // is it correct in this context? - } - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }) - .or_else([&](auto&& _err) -> rfl::Result { - _errors.emplace_back(std::move(_err)); - if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }); + auto res = Head::validate(_value); + if (!res) { + _errors.emplace_back(std::move(res).error()); + } + if constexpr (sizeof...(Tail) == 0) { + if (_errors.size() == sizeof...(Cs)) { + return _value; + } + return error(Error(make_error_message(_errors), + ErrorKind::constraint_violation, + internal::BuiltinErrorCode::one_of)); + } else { + return validate_impl(_value, std::move(_errors)); + } } }; diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index b1dcbc040..a48d487d2 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -38,7 +38,8 @@ struct PatternValidator { std::stringstream stream; stream << "String '" << _str << "' did not match format '" << _name.str() << "': '" << _regex.str() << "'."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::pattern)); } } diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 104bf0d8f..22e171cd8 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -7,6 +7,11 @@ #include "internal/cpp20/Result.hpp" #endif +#include +#include +#include +#include + #include "internal/Error.hpp" namespace rfl { @@ -84,6 +89,51 @@ inline Unexpected error(std::string _what, const ErrorKind _kind, return Unexpected(Error(std::move(_what), std::move(details))); } +/// Shorthand for a classified unexpected error with a machine-readable code. +/// Constrained template so braced-init path calls such as +/// `rfl::error("msg", kind, {"field"})` and `rfl::error("msg", kind, {})` +/// remain unambiguously resolved to the path overload above. +template + requires(std::convertible_to && + !std::is_null_pointer_v>) +inline Unexpected error(std::string _what, const ErrorKind _kind, + Code&& _code) { + std::string_view code_view; + if constexpr (std::is_pointer_v>) { + code_view = _code ? std::string_view(_code) : std::string_view{}; + } else { + code_view = std::string_view(std::forward(_code)); + } + return Unexpected(Error(std::move(_what), _kind, code_view)); +} + +/// Shorthand for a classified unexpected error at a nested path with a +/// machine-readable code. +template + requires(std::convertible_to && + !std::is_null_pointer_v>) +inline Unexpected error(std::string _what, const ErrorKind _kind, + std::vector _path, + Code&& _code) { + std::string_view code_view; + if constexpr (std::is_pointer_v>) { + code_view = _code ? std::string_view(_code) : std::string_view{}; + } else { + code_view = std::string_view(std::forward(_code)); + } + if (_path.empty()) { + return Unexpected(Error(std::move(_what), _kind, code_view)); + } + std::vector details; + details.push_back(ErrorDetail{ + .path = std::move(_path), + .message = _what, + .kind = _kind, + .code = std::string(code_view), + }); + return Unexpected(Error(std::move(_what), std::move(details))); +} + } // namespace rfl #ifdef REFLECTCPP_USE_STD_EXPECTED diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index 5148b0b00..c8ffc1426 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -6,6 +6,7 @@ #include "Ref.hpp" #include "Result.hpp" +#include "internal/validator_code.hpp" #include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -22,7 +23,9 @@ struct Size { static rfl::Result validate(T _t) { auto res = V::validate(_t.size()); if (!res) { - return error("Size validation failed: " + res.error().what()); + return error(internal::compose_prefixed_validator_error( + std::move(res).error(), "Size validation failed: ", "size.", + internal::BuiltinErrorCode::size, internal::compose_size_code)); } return std::move(_t); } diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 1d9373b63..aa3cc68f9 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -10,6 +10,7 @@ #include "AllOf.hpp" #include "Result.hpp" #include "internal/HasValidation.hpp" +#include "internal/validator_code.hpp" namespace rfl { @@ -35,7 +36,8 @@ struct Validator { try { return wrap_validated(ValidationType::validate(_value)); } catch (std::exception& e) { - return error(e.what(), ErrorKind::constraint_violation); + return error(e.what(), ErrorKind::constraint_violation, + internal::validator_code()); } } @@ -47,7 +49,8 @@ struct Validator { try { return wrap_validated(ValidationType::validate(std::move(_value))); } catch (std::exception& e) { - return error(e.what(), ErrorKind::constraint_violation); + return error(e.what(), ErrorKind::constraint_violation, + internal::validator_code()); } } @@ -202,6 +205,8 @@ struct Validator { if (!_res) { Error err = std::move(_res).error(); internal::set_error_kind_if_other(err, ErrorKind::constraint_violation); + internal::set_error_code_if_empty( + err, internal::validator_code()); return error(std::move(err)); } return Validator(AlreadyValidated{}, std::move(*_res)); diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 1233f2f09..f8b02a57d 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -25,7 +25,8 @@ struct EqualTo { std::stringstream stream; stream << "Value expected to be equal to " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::equal_to)); } return _value; } @@ -64,7 +65,8 @@ struct Minimum { std::stringstream stream; stream << "Value expected to be greater than or equal to " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::minimum)); } return _value; } @@ -103,7 +105,8 @@ struct ExclusiveMinimum { std::stringstream stream; stream << "Value expected to be greater than " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::exclusive_minimum)); } return _value; } @@ -142,7 +145,8 @@ struct Maximum { std::stringstream stream; stream << "Value expected to be less than or equal to " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::maximum)); } return _value; } @@ -180,7 +184,8 @@ struct ExclusiveMaximum { std::stringstream stream; stream << "Value expected to be less than " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::exclusive_maximum)); } return _value; } @@ -218,7 +223,8 @@ struct NotEqualTo { std::stringstream stream; stream << "Value expected not to be equal to " << threshold << ", but got " << _value << "."; - return error(stream.str()); + return error(Error(stream.str(), ErrorKind::constraint_violation, + internal::BuiltinErrorCode::not_equal_to)); } return _value; } diff --git a/include/rfl/internal/Error.hpp b/include/rfl/internal/Error.hpp index 11a5f58af..695d461dd 100644 --- a/include/rfl/internal/Error.hpp +++ b/include/rfl/internal/Error.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,206 @@ enum class ErrorKind : std::uint8_t { constraint_violation, }; +/// Internal compact tags for built-in validator rule codes so leaf validator +/// errors carry a machine-readable code inline in Error without increasing +/// sizeof(Error) or allocating OptionalDetails. +enum class BuiltinErrorCode : std::uint8_t { + none = 0, + equal_to, + not_equal_to, + minimum, + exclusive_minimum, + maximum, + exclusive_maximum, + pattern, + any_of, + one_of, + size, + size_equal_to, + size_not_equal_to, + size_minimum, + size_exclusive_minimum, + size_maximum, + size_exclusive_maximum, + size_any_of, + size_one_of, + code_points, + code_points_equal_to, + code_points_not_equal_to, + code_points_minimum, + code_points_exclusive_minimum, + code_points_maximum, + code_points_exclusive_maximum, + code_points_any_of, + code_points_one_of, +}; + +/// Returns the canonical wire string for a BuiltinErrorCode, or empty if none. +constexpr std::string_view builtin_error_code_str( + const BuiltinErrorCode _code) noexcept { + switch (_code) { + case BuiltinErrorCode::none: + return {}; + case BuiltinErrorCode::equal_to: + return "equal_to"; + case BuiltinErrorCode::not_equal_to: + return "not_equal_to"; + case BuiltinErrorCode::minimum: + return "minimum"; + case BuiltinErrorCode::exclusive_minimum: + return "exclusive_minimum"; + case BuiltinErrorCode::maximum: + return "maximum"; + case BuiltinErrorCode::exclusive_maximum: + return "exclusive_maximum"; + case BuiltinErrorCode::pattern: + return "pattern"; + case BuiltinErrorCode::any_of: + return "any_of"; + case BuiltinErrorCode::one_of: + return "one_of"; + case BuiltinErrorCode::size: + return "size"; + case BuiltinErrorCode::size_equal_to: + return "size.equal_to"; + case BuiltinErrorCode::size_not_equal_to: + return "size.not_equal_to"; + case BuiltinErrorCode::size_minimum: + return "size.minimum"; + case BuiltinErrorCode::size_exclusive_minimum: + return "size.exclusive_minimum"; + case BuiltinErrorCode::size_maximum: + return "size.maximum"; + case BuiltinErrorCode::size_exclusive_maximum: + return "size.exclusive_maximum"; + case BuiltinErrorCode::size_any_of: + return "size.any_of"; + case BuiltinErrorCode::size_one_of: + return "size.one_of"; + case BuiltinErrorCode::code_points: + return "code_points"; + case BuiltinErrorCode::code_points_equal_to: + return "code_points.equal_to"; + case BuiltinErrorCode::code_points_not_equal_to: + return "code_points.not_equal_to"; + case BuiltinErrorCode::code_points_minimum: + return "code_points.minimum"; + case BuiltinErrorCode::code_points_exclusive_minimum: + return "code_points.exclusive_minimum"; + case BuiltinErrorCode::code_points_maximum: + return "code_points.maximum"; + case BuiltinErrorCode::code_points_exclusive_maximum: + return "code_points.exclusive_maximum"; + case BuiltinErrorCode::code_points_any_of: + return "code_points.any_of"; + case BuiltinErrorCode::code_points_one_of: + return "code_points.one_of"; + } + return {}; +} + +/// Maps a canonical wire string back to its compact BuiltinErrorCode if it is +/// one of the built-in validator codes, or BuiltinErrorCode::none otherwise. +constexpr BuiltinErrorCode parse_builtin_error_code( + const std::string_view _code) noexcept { + if (_code.empty()) { + return BuiltinErrorCode::none; + } + if (_code == "equal_to") return BuiltinErrorCode::equal_to; + if (_code == "not_equal_to") return BuiltinErrorCode::not_equal_to; + if (_code == "minimum") return BuiltinErrorCode::minimum; + if (_code == "exclusive_minimum") return BuiltinErrorCode::exclusive_minimum; + if (_code == "maximum") return BuiltinErrorCode::maximum; + if (_code == "exclusive_maximum") return BuiltinErrorCode::exclusive_maximum; + if (_code == "pattern") return BuiltinErrorCode::pattern; + if (_code == "any_of") return BuiltinErrorCode::any_of; + if (_code == "one_of") return BuiltinErrorCode::one_of; + if (_code == "size") return BuiltinErrorCode::size; + if (_code == "size.equal_to") return BuiltinErrorCode::size_equal_to; + if (_code == "size.not_equal_to") return BuiltinErrorCode::size_not_equal_to; + if (_code == "size.minimum") return BuiltinErrorCode::size_minimum; + if (_code == "size.exclusive_minimum") + return BuiltinErrorCode::size_exclusive_minimum; + if (_code == "size.maximum") return BuiltinErrorCode::size_maximum; + if (_code == "size.exclusive_maximum") + return BuiltinErrorCode::size_exclusive_maximum; + if (_code == "size.any_of") return BuiltinErrorCode::size_any_of; + if (_code == "size.one_of") return BuiltinErrorCode::size_one_of; + if (_code == "code_points") return BuiltinErrorCode::code_points; + if (_code == "code_points.equal_to") + return BuiltinErrorCode::code_points_equal_to; + if (_code == "code_points.not_equal_to") + return BuiltinErrorCode::code_points_not_equal_to; + if (_code == "code_points.minimum") + return BuiltinErrorCode::code_points_minimum; + if (_code == "code_points.exclusive_minimum") + return BuiltinErrorCode::code_points_exclusive_minimum; + if (_code == "code_points.maximum") + return BuiltinErrorCode::code_points_maximum; + if (_code == "code_points.exclusive_maximum") + return BuiltinErrorCode::code_points_exclusive_maximum; + if (_code == "code_points.any_of") + return BuiltinErrorCode::code_points_any_of; + if (_code == "code_points.one_of") + return BuiltinErrorCode::code_points_one_of; + return BuiltinErrorCode::none; +} + +/// Composes a BuiltinErrorCode under the `size.*` namespace when possible. +constexpr BuiltinErrorCode compose_size_code( + const BuiltinErrorCode _inner) noexcept { + switch (_inner) { + case BuiltinErrorCode::none: + return BuiltinErrorCode::size; + case BuiltinErrorCode::equal_to: + return BuiltinErrorCode::size_equal_to; + case BuiltinErrorCode::not_equal_to: + return BuiltinErrorCode::size_not_equal_to; + case BuiltinErrorCode::minimum: + return BuiltinErrorCode::size_minimum; + case BuiltinErrorCode::exclusive_minimum: + return BuiltinErrorCode::size_exclusive_minimum; + case BuiltinErrorCode::maximum: + return BuiltinErrorCode::size_maximum; + case BuiltinErrorCode::exclusive_maximum: + return BuiltinErrorCode::size_exclusive_maximum; + case BuiltinErrorCode::any_of: + return BuiltinErrorCode::size_any_of; + case BuiltinErrorCode::one_of: + return BuiltinErrorCode::size_one_of; + default: + return BuiltinErrorCode::none; + } +} + +/// Composes a BuiltinErrorCode under the `code_points.*` namespace when +/// possible. +constexpr BuiltinErrorCode compose_code_points_code( + const BuiltinErrorCode _inner) noexcept { + switch (_inner) { + case BuiltinErrorCode::none: + return BuiltinErrorCode::code_points; + case BuiltinErrorCode::equal_to: + return BuiltinErrorCode::code_points_equal_to; + case BuiltinErrorCode::not_equal_to: + return BuiltinErrorCode::code_points_not_equal_to; + case BuiltinErrorCode::minimum: + return BuiltinErrorCode::code_points_minimum; + case BuiltinErrorCode::exclusive_minimum: + return BuiltinErrorCode::code_points_exclusive_minimum; + case BuiltinErrorCode::maximum: + return BuiltinErrorCode::code_points_maximum; + case BuiltinErrorCode::exclusive_maximum: + return BuiltinErrorCode::code_points_exclusive_maximum; + case BuiltinErrorCode::any_of: + return BuiltinErrorCode::code_points_any_of; + case BuiltinErrorCode::one_of: + return BuiltinErrorCode::code_points_one_of; + default: + return BuiltinErrorCode::none; + } +} + /// Describes a single failure contained in an Error: where it occurred and /// what went wrong. struct ErrorDetail { @@ -85,6 +286,11 @@ struct ErrorDetail { /// The coarse category of this failure. ErrorKind kind = ErrorKind::other; + /// Optional machine-readable rule or error code (for example, `"minimum"`, + /// `"size.minimum"`, `"pattern"`, or a custom validator code). Empty when + /// no finer-grained code applies. + std::string code = {}; + bool operator==(const ErrorDetail&) const = default; }; @@ -117,6 +323,35 @@ class Error { Error(std::string&& _what, const ErrorKind _kind) : what_(std::move(_what)), kind_(_kind) {} + /// Constructs a classified leaf error with a built-in rule code, without + /// allocating an explicit detail vector. + Error(std::string _what, const ErrorKind _kind, + const BuiltinErrorCode _builtin_code) + : what_(std::move(_what)), kind_(_kind), builtin_code_(_builtin_code) {} + + /// Constructs a classified error with a machine-readable code. + /// Built-in codes are stored inline without allocating details; custom codes + /// are stored in details_. + Error(std::string _what, const ErrorKind _kind, const std::string_view _code) + : what_(std::move(_what)), kind_(_kind) { + if (_code.empty()) { + return; + } + const auto builtin = parse_builtin_error_code(_code); + if (builtin != BuiltinErrorCode::none) { + builtin_code_ = builtin; + return; + } + std::vector details; + details.push_back(ErrorDetail{ + .path = {}, + .message = what_, + .kind = _kind, + .code = std::string(_code), + }); + details_ = OptionalDetails(std::move(details)); + } + /// Constructs an error with a message and the individual failures it /// summarizes. /// @param _what The error message describing what went wrong @@ -163,12 +398,28 @@ class Error { : kind_; } + /// Returns the machine-readable error code of this error, or an empty view + /// when none is set. For multi-error results, returns the code of the first + /// detail. + /// Note: For custom (non-built-in) codes, the returned string_view refers to + /// storage owned by this Error and must not outlive it. + std::string_view code() const noexcept { + if (details_.has_value() && !(*details_).empty()) { + return (*details_).front().code; + } + return builtin_error_code_str(builtin_code_); + } + /// Returns the individual failures summarized by what(), each with the /// location at which it occurred. An error that was constructed from a /// message only is reported as a single failure at the root. std::vector details() const& { if (!details_.has_value()) { - return {ErrorDetail{.path = {}, .message = what_, .kind = kind_}}; + return {ErrorDetail{ + .path = {}, + .message = what_, + .kind = kind_, + .code = std::string(builtin_error_code_str(builtin_code_))}}; } return *details_; } @@ -177,8 +428,11 @@ class Error { /// moved from state. std::vector details() && { if (!details_.has_value()) { - return { - ErrorDetail{.path = {}, .message = std::move(what_), .kind = kind_}}; + return {ErrorDetail{ + .path = {}, + .message = std::move(what_), + .kind = kind_, + .code = std::string(builtin_error_code_str(builtin_code_))}}; } return std::move(*details_); } @@ -188,6 +442,11 @@ class Error { return _err.details_.has_value(); } + friend BuiltinErrorCode builtin_error_code_of(const Error& _err) noexcept { + return _err.details_.has_value() ? BuiltinErrorCode::none + : _err.builtin_code_; + } + friend void set_error_kind_if_other(Error& _err, const ErrorKind _kind) noexcept { if (_kind == ErrorKind::other) { @@ -206,6 +465,36 @@ class Error { } } + friend void set_error_code_if_empty(Error& _err, + const std::string_view _code) { + if (_code.empty()) { + return; + } + if (!_err.details_.has_value()) { + if (_err.builtin_code_ != BuiltinErrorCode::none) { + return; + } + const auto builtin = parse_builtin_error_code(_code); + if (builtin != BuiltinErrorCode::none) { + _err.builtin_code_ = builtin; + return; + } + std::vector details; + details.push_back(ErrorDetail{ + .path = {}, + .message = _err.what_, + .kind = _err.kind_, + .code = std::string(_code), + }); + _err.details_ = OptionalDetails(std::move(details)); + return; + } + for (auto& detail : *_err.details_) { + if (detail.code.empty()) { + detail.code = std::string(_code); + } + } + } /// Either nothing or a heap-allocated vector of details, deep-copied along /// with the Error. Holding nothing is the common case: it means that the /// Error is just its message, and it does not allocate. @@ -269,15 +558,26 @@ class Error { /// Coarse category for a leaf error when details_ holds nothing. ErrorKind kind_ = ErrorKind::other; + + /// Compact built-in rule code for a leaf error when details_ holds nothing. + /// Packed into ErrorKind's tail padding so sizeof(Error) does not grow. + BuiltinErrorCode builtin_code_ = BuiltinErrorCode::none; }; /// Returns whether _err has a heap-allocated detail vector. bool has_allocated_details(const Error& _err) noexcept; +/// Returns the inline BuiltinErrorCode for a leaf error (none if detailed). +BuiltinErrorCode builtin_error_code_of(const Error& _err) noexcept; + /// Replaces ErrorKind::other with _kind in place without copying what_ or /// allocating details on leaf errors. void set_error_kind_if_other(Error& _err, ErrorKind _kind) noexcept; +/// Attaches _code to _err (or to each uncoded detail) when no code is already +/// present. Preserves zero-allocation for built-in codes on leaf errors. +void set_error_code_if_empty(Error& _err, std::string_view _code); + } // namespace rfl::internal #endif diff --git a/include/rfl/internal/validator_code.hpp b/include/rfl/internal/validator_code.hpp new file mode 100644 index 000000000..812c83a49 --- /dev/null +++ b/include/rfl/internal/validator_code.hpp @@ -0,0 +1,74 @@ +#ifndef RFL_INTERNAL_VALIDATOR_CODE_HPP_ +#define RFL_INTERNAL_VALIDATOR_CODE_HPP_ + +#include +#include +#include +#include +#include + +#include "Error.hpp" + +namespace rfl::internal { + +/// Extracts an optional declarative rule code from a validator type V. +/// Supports: +/// - `static constexpr std::string_view code = "...";` +/// - `static constexpr const char* code = "...";` / `char code[] = "...";` +/// - `static constexpr rfl::internal::StringLiteral code = "...";` +template +constexpr std::string_view validator_code() noexcept { + if constexpr (requires { + &V::code; + requires !std::is_member_pointer_v; + { V::code.string_view() } + -> std::convertible_to; + }) { + return V::code.string_view(); + } else if constexpr (requires { + &V::code; + requires !std::is_member_pointer_v; + { V::code } -> std::convertible_to; + }) { + using CodeT = std::remove_cvref_t; + if constexpr (std::is_null_pointer_v) { + return {}; + } else if constexpr (std::is_pointer_v) { + return V::code ? std::string_view(V::code) : std::string_view{}; + } else { + return std::string_view(V::code); + } + } else { + return {}; + } +} + +/// Composes a wrapped validator error (e.g. `Size` or `CodePoints`) +/// preserving zero-allocation built-in codes whenever possible. +template +Error compose_prefixed_validator_error(Error&& _inner_err, + const std::string_view _msg_prefix, + const std::string_view _code_prefix, + const BuiltinErrorCode _fallback_builtin, + ComposeFn&& _compose_builtin) { + set_error_code_if_empty(_inner_err, validator_code()); + auto msg = std::string(_msg_prefix) + _inner_err.what(); + const auto inner_builtin = builtin_error_code_of(_inner_err); + if (inner_builtin != BuiltinErrorCode::none) { + const auto composed = _compose_builtin(inner_builtin); + if (composed != BuiltinErrorCode::none) { + return Error(std::move(msg), ErrorKind::constraint_violation, composed); + } + } + const auto inner_code = _inner_err.code(); + if (inner_code.empty()) { + return Error(std::move(msg), ErrorKind::constraint_violation, + _fallback_builtin); + } + return Error(std::move(msg), ErrorKind::constraint_violation, + std::string(_code_prefix) + std::string(inner_code)); +} + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index c98ca1022..b42394c36 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -76,14 +76,22 @@ class MapReader { "Expected an rvalue"); const auto to_pair = [&](auto&& _key) -> Result> { - try { - using K = decltype(_key); - return std::make_pair(KeyType(std::forward(_key)), - std::move(_pair.second)); - } catch (std::exception& e) { - if constexpr (internal::is_validator_v) { - return error(e.what(), ErrorKind::constraint_violation); - } else { + using K = decltype(_key); + if constexpr (internal::is_validator_v) { + try { + return KeyType::from_value(std::forward(_key)) + .transform([&](KeyType&& _validated) { + return std::make_pair(std::move(_validated), + std::move(_pair.second)); + }); + } catch (std::exception& e) { + return error(e.what(), ErrorKind::invalid_value); + } + } else { + try { + return std::make_pair(KeyType(std::forward(_key)), + std::move(_pair.second)); + } catch (std::exception& e) { return error(e.what(), ErrorKind::invalid_value); } } diff --git a/include/rfl/parsing/wrap_error.hpp b/include/rfl/parsing/wrap_error.hpp index 58f30639e..43426f462 100644 --- a/include/rfl/parsing/wrap_error.hpp +++ b/include/rfl/parsing/wrap_error.hpp @@ -59,7 +59,8 @@ RFL_COLD inline Error wrap_field_error(const std::string_view _name, RFL_COLD inline Error wrap_error(const std::string_view _prefix, Error&& _err) { auto what = std::string(_prefix) + _err.what(); if (!internal::has_allocated_details(_err)) { - return Error(std::move(what), _err.kind()); + return Error(std::move(what), _err.kind(), + internal::builtin_error_code_of(_err)); } auto details = std::move(_err).details(); for (auto& detail : details) { diff --git a/tests/json/test_error_code.cpp b/tests/json/test_error_code.cpp new file mode 100644 index 000000000..5e1ab9212 --- /dev/null +++ b/tests/json/test_error_code.cpp @@ -0,0 +1,464 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_json_error_code { + +using Path = std::vector; + +struct MustBeEven { + static constexpr std::string_view code = "even"; + static rfl::Result validate(const int _v) { + if (_v % 2 != 0) { + return rfl::error("Expected an even integer."); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct EvenLength { + static constexpr const char* code = "even_length"; + static rfl::Result validate(const size_t _n) { + if (_n % 2 != 0) { + return rfl::error("Expected an even length."); + } + return _n; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct UncodedSizeRule { + static rfl::Result validate(const size_t _n) { + if (_n == 3) { + return rfl::error("Length 3 is forbidden."); + } + return _n; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct DynamicCodeValidator { + static constexpr std::string_view code = "fallback_code"; + static rfl::Result validate(const int _v) { + if (_v < 0) { + return rfl::error("Must not be negative.", + rfl::ErrorKind::constraint_violation, "non_negative"); + } + if (_v == 13) { + return rfl::error("Unlucky number."); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct ThrowingCustomValidator { + static constexpr rfl::internal::StringLiteral code = "boom"; + static rfl::Result validate(const int _v) { + if (_v == 0) { + throw std::runtime_error("cannot be zero"); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct NonStaticCodeValidator { + std::string code = "should_not_be_used"; + static rfl::Result validate(const int _v) { + if (_v < 0) { + return rfl::error("must be non-negative"); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct NullPtrCodeValidator { + static constexpr const char* code = nullptr; + static rfl::Result validate(const int _v) { + if (_v < 0) { + return rfl::error("bad"); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct CharArrayCodeValidator { + static constexpr char code[] = "char_array_rule"; + static rfl::Result validate(const int _v) { + if (_v < 0) { + return rfl::error("bad"); + } + return _v; + } + template + static rfl::parsing::schema::ValidationType to_schema() { + return rfl::parsing::schema::ValidationType{ + rfl::parsing::schema::ValidationType::AllOf{}}; + } +}; + +struct MediaRequest { + rfl::Validator>> item_name; + rfl::Validator, rfl::Maximum<100>> volume; +}; + +TEST(json, test_error_code_builtin_validators_zero_alloc) { + // sizeof(Error) must match the pre-code layout exactly (builtin_code_ packs + // into ErrorKind's existing tail padding). + struct PreCodeErrorLayout { + std::string what_; + void* details_ptr_; + rfl::ErrorKind kind_; + }; + static_assert(sizeof(rfl::Error) == sizeof(PreCodeErrorLayout)); + + { + const auto res = rfl::json::read>>("4"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "minimum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + EXPECT_EQ(res.error().details().at(0).code, "minimum"); + } + { + const auto res = + rfl::json::read>>("5"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "exclusive_minimum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = + rfl::json::read>>("11"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "maximum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = + rfl::json::read>>("10"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "exclusive_maximum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = + rfl::json::read>>("41"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "equal_to"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = + rfl::json::read>>("0"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "not_equal_to"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = rfl::json::read("\"not-an-email\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "pattern"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = rfl::json::read< + rfl::Validator, rfl::EqualTo<2>>>>("3"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "any_of"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + using OneOfRange = + rfl::Validator, rfl::Maximum<10>>>; + // Both constraints pass -> OneOf fails with code "one_of". + const auto both_pass = rfl::json::read("5"); + ASSERT_FALSE(both_pass); + EXPECT_EQ(both_pass.error().code(), "one_of"); + EXPECT_FALSE(rfl::internal::has_allocated_details(both_pass.error())); + + // Exactly one constraint passes -> succeeds. + const auto one_pass_hi = rfl::json::read("15"); + ASSERT_TRUE(one_pass_hi) << one_pass_hi.error().what(); + EXPECT_EQ(one_pass_hi->value(), 15); + const auto one_pass_lo = rfl::json::read("-5"); + ASSERT_TRUE(one_pass_lo) << one_pass_lo.error().what(); + EXPECT_EQ(one_pass_lo->value(), -5); + + // Zero constraints pass -> OneOf fails with code "one_of". + const auto none_pass = rfl::json::read< + rfl::Validator, rfl::EqualTo<2>>>>("3"); + ASSERT_FALSE(none_pass); + EXPECT_EQ(none_pass.error().code(), "one_of"); + EXPECT_FALSE(rfl::internal::has_allocated_details(none_pass.error())); + } +} + +TEST(json, test_error_code_size_and_code_points_composition) { + { + const auto res = rfl::json::read< + rfl::Validator>>>("\"\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "size.minimum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = rfl::json::read, + rfl::Size, rfl::Maximum<2>>>>>("[1,2,3]"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "size.maximum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = rfl::json::read< + rfl::Validator>>>( + "\"abc\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "code_points.maximum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = + rfl::json::read>>( + "\"abc\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "size.even_length"); + } + { + const auto res = rfl::json::read< + rfl::Validator>>("\"abc\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "size"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + const auto res = rfl::json::read< + rfl::Validator>>( + "\"abc\""); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "code_points"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } +} + +TEST(json, test_error_code_custom_validators_and_all_of) { + { + const auto res = + rfl::json::read>>("3"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "even"); + } + { + const auto res = + rfl::json::read>>("-2"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "minimum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + } + { + // Dynamic explicit code overrides declarative static fallback_code. + const auto res1 = + rfl::json::read>("-5"); + ASSERT_FALSE(res1); + EXPECT_EQ(res1.error().code(), "non_negative"); + + // Uncoded error falls back to static declarative code. + const auto res2 = + rfl::json::read>("13"); + ASSERT_FALSE(res2); + EXPECT_EQ(res2.error().code(), "fallback_code"); + } + { + // Exception thrown inside validate() still attaches declarative code. + const auto res = + rfl::json::read>("0"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), "boom"); + } + { + // Non-static `code` member is ignored cleanly (must not fail to compile). + const auto res = + rfl::json::read>("-1"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(res.error().code(), ""); + } + { + // static constexpr const char* code = nullptr produces empty code safely. + const auto res = + rfl::json::read>("-1"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), ""); + } + { + // static constexpr char code[] = "..." attaches code properly. + const auto res = + rfl::json::read>("-1"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().code(), "char_array_rule"); + } +} + +TEST(json, test_error_code_nested_struct_classification_and_helpers) { + // Classify constraint violations purely via ErrorDetail::code without string + // prefix matching. + const auto classify_status = [](const rfl::ErrorDetail& _d) -> int { + if (_d.kind == rfl::ErrorKind::constraint_violation) { + if (_d.code == "size.minimum" || _d.code == "code_points.minimum") { + return 403; + } + return 402; + } + return 400; + }; + + const auto res = rfl::json::read( + R"({"item_name": "", "volume": 150})"); + ASSERT_FALSE(res); + const auto details = res.error().details(); + ASSERT_EQ(details.size(), 2u); + + EXPECT_EQ(details[0].path, (Path{"item_name"})); + EXPECT_EQ(details[0].kind, rfl::ErrorKind::constraint_violation); + EXPECT_EQ(details[0].code, "size.minimum"); + EXPECT_EQ(classify_status(details[0]), 403); + + EXPECT_EQ(details[1].path, (Path{"volume"})); + EXPECT_EQ(details[1].kind, rfl::ErrorKind::constraint_violation); + EXPECT_EQ(details[1].code, "maximum"); + EXPECT_EQ(classify_status(details[1]), 402); + + // Error::code() returns the first detail's code on multi-error results. + EXPECT_EQ(res.error().code(), "size.minimum"); + + // rfl::error helpers with code + path and JSON round-trip. + const auto helper_leaf = + rfl::error("bad", rfl::ErrorKind::constraint_violation, "custom_rule"); + EXPECT_EQ(helper_leaf.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(helper_leaf.error().code(), "custom_rule"); + + const auto helper_nested = rfl::error( + "bad", rfl::ErrorKind::constraint_violation, {"items", size_t{1}}, + "custom_rule"); + ASSERT_EQ(helper_nested.error().details().size(), 1u); + EXPECT_EQ(helper_nested.error().details()[0].path, (Path{"items", size_t{1}})); + EXPECT_EQ(helper_nested.error().details()[0].code, "custom_rule"); + + // Backward-compatible empty/braced path overloads remain unambiguous. + const auto empty_path = rfl::error("bad", rfl::ErrorKind::invalid_value, {}); + EXPECT_EQ(empty_path.error().code(), ""); + const auto braced_path = + rfl::error("bad", rfl::ErrorKind::invalid_value, {"port"}); + EXPECT_EQ(braced_path.error().details()[0].path, (Path{"port"})); + EXPECT_EQ(braced_path.error().details()[0].code, ""); + + // JSON serialization round-trip preserves ErrorDetail::code. + const auto json_str = rfl::json::write(details); + EXPECT_NE(json_str.find(R"("code":"size.minimum")"), std::string::npos) + << json_str; + const auto roundtrip = + rfl::json::read>(json_str); + ASSERT_TRUE(roundtrip) << roundtrip.error().what(); + EXPECT_EQ(*roundtrip, details); + + // Runtime null const char* and std::string_view 4-arg helper safety. + const char* null_code = nullptr; + const auto null_err = + rfl::error("bad", rfl::ErrorKind::constraint_violation, null_code); + EXPECT_EQ(null_err.error().code(), ""); + EXPECT_FALSE(rfl::internal::has_allocated_details(null_err.error())); + + const std::string_view sv_code = "sv_rule"; + const auto sv_nested = rfl::error( + "bad", rfl::ErrorKind::constraint_violation, {"a"}, sv_code); + EXPECT_EQ(sv_nested.error().code(), "sv_rule"); + EXPECT_EQ(sv_nested.error().details()[0].path, (Path{"a"})); + + const auto null_nested = rfl::error( + "bad", rfl::ErrorKind::constraint_violation, {"a"}, null_code); + EXPECT_EQ(null_nested.error().code(), ""); + + const auto empty_path_coded = rfl::error( + "bad", rfl::ErrorKind::constraint_violation, {}, "custom_rule"); + EXPECT_EQ(empty_path_coded.error().code(), "custom_rule"); + EXPECT_TRUE(empty_path_coded.error().details()[0].path.empty()); + + // Propagation through wrap_error (prefix-only zero-alloc) and nested path + // wrapping. + auto leaf = rfl::Error("too small", rfl::ErrorKind::constraint_violation, + "minimum"); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf)); + auto prefixed = rfl::parsing::wrap_error("ctx: ", std::move(leaf)); + EXPECT_EQ(prefixed.code(), "minimum"); + EXPECT_EQ(prefixed.kind(), rfl::ErrorKind::constraint_violation); + EXPECT_FALSE(rfl::internal::has_allocated_details(prefixed)); + + auto field_wrapped = + rfl::parsing::wrap_field_error("port", std::move(prefixed)); + auto chained = rfl::parsing::wrap_error( + "Failed to parse element 0: ", size_t{0}, std::move(field_wrapped)); + ASSERT_EQ(chained.details().size(), 1u); + EXPECT_EQ(chained.details()[0].path, (Path{size_t{0}, "port"})); + EXPECT_EQ(chained.details()[0].code, "minimum"); + + // Validated map keys (string and numeric) preserve ErrorDetail::code via + // MapReader. + using ValidKey = rfl::Validator>>; + const auto bad_map_key = + rfl::json::read>(R"({"ab": 1})"); + ASSERT_FALSE(bad_map_key); + EXPECT_EQ(bad_map_key.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_EQ(bad_map_key.error().code(), "size.minimum"); + + using ValidIntKey = rfl::Validator>; + const auto bad_int_map_key = + rfl::json::read>(R"({"0": 1})"); + ASSERT_FALSE(bad_int_map_key); + EXPECT_EQ(bad_int_map_key.error().kind(), + rfl::ErrorKind::constraint_violation); + EXPECT_EQ(bad_int_map_key.error().code(), "minimum"); +} + +} // namespace test_json_error_code diff --git a/tests/json/test_error_details.cpp b/tests/json/test_error_details.cpp index 26137b10d..d3149af3e 100644 --- a/tests/json/test_error_details.cpp +++ b/tests/json/test_error_details.cpp @@ -37,7 +37,8 @@ TEST(json, test_error_details_of_top_level_fields) { {{.path = {"input_file"}, .message = "Size validation failed: Value expected to be greater " "than or equal to 5, but got 4.", - .kind = rfl::ErrorKind::constraint_violation}, + .kind = rfl::ErrorKind::constraint_violation, + .code = "size.minimum"}, {.path = {"output_file"}, .message = "Field named 'output_file' not found.", .kind = rfl::ErrorKind::missing_field}});