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
12 changes: 10 additions & 2 deletions docs/content/result.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
```
Expand All @@ -174,7 +178,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`.

Expand All @@ -194,9 +198,11 @@ const auto result = rfl::json::read<Request, rfl::SnakeCaseToCamelCase>(
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."
}
```
Expand All @@ -205,11 +211,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("error message"))`. You can also pass an `rfl::ErrorKind` (and optionally a `std::vector<rfl::ErrorDetail::PathSegment>` path):
`rfl::error("error message")` is a simple utility function for `rfl::Unexpected<Error>(Error("error message"))`. You can also pass an `rfl::ErrorKind`, an optional `std::vector<rfl::ErrorDetail::PathSegment>` 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(...)`
Expand Down
13 changes: 10 additions & 3 deletions include/rfl/AllOf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <vector>

#include "Result.hpp"
#include "internal/validator_code.hpp"
#include "parsing/schema/ValidationType.hpp"

namespace rfl {
Expand Down Expand Up @@ -37,17 +38,23 @@ struct AllOf {
try {
auto res = Head::validate(std::move(_value));
if (!res) {
return 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<Head>());
return error(std::move(err));
}
if constexpr (sizeof...(Tail) == 0) {
return res;
} else {
return validate_impl<T, Tail...>(std::move(*res));
}
} catch (const std::exception& e) {
return error(e.what());
return error(e.what(), ErrorKind::constraint_violation,
internal::validator_code<Head>());
} catch (...) {
return error("Unknown exception during validation.");
return error("Unknown exception during validation.",
ErrorKind::constraint_violation,
internal::validator_code<Head>());
}
}
};
Expand Down
4 changes: 3 additions & 1 deletion include/rfl/AnyOf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ struct AnyOf {
const auto handle_err = [&](Error&& _err) -> rfl::Result<T> {
_errors.push_back(std::forward<Error>(_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<T, Tail...>(
_value, std::forward<std::vector<Error>>(_errors));
Expand Down
8 changes: 6 additions & 2 deletions include/rfl/CodePoints.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include "Result.hpp"
#include "Size.hpp"
#include "internal/validator_code.hpp"
#include "parsing/schema/ValidationType.hpp"

namespace rfl {
Expand Down Expand Up @@ -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<V>(
std::move(res).error(),
"Code point count validation failed: ", "code_points.",
internal::BuiltinErrorCode::code_points,
internal::compose_code_points_code));
}
return std::move(_t);
}
Expand Down
4 changes: 3 additions & 1 deletion include/rfl/OneOf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ struct OneOf {
if (_errors.size() == sizeof...(Cs)) {
return _value;
}
return error(make_error_message(_errors));
return error(Error(make_error_message(_errors),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::one_of));
} else {
return validate_impl<T, Tail...>(_value, std::move(_errors));
}
Expand Down
6 changes: 4 additions & 2 deletions include/rfl/PatternValidator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ struct PatternValidator {
ctll::construct_from_pointer, _regex.arr_.data()}>(_str)) {
return std::move(_str);
} else {
return error("String '" + _str + "' did not match format '" +
_name.str() + "': '" + _regex.str() + "'.");
return error(Error("String '" + _str + "' did not match format '" +
_name.str() + "': '" + _regex.str() + "'.",
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::pattern));
}
}

Expand Down
50 changes: 50 additions & 0 deletions include/rfl/Result.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
#include "internal/cpp20/Result.hpp"
#endif

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

#include "internal/Error.hpp"

namespace rfl {
Expand Down Expand Up @@ -84,6 +89,51 @@ inline Unexpected<Error> error(std::string _what, const ErrorKind _kind,
return Unexpected<Error>(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 <class Code>
requires(std::convertible_to<Code, std::string_view> &&
!std::is_null_pointer_v<std::remove_cvref_t<Code>>)
inline Unexpected<Error> error(std::string _what, const ErrorKind _kind,
Code&& _code) {
std::string_view code_view;
if constexpr (std::is_pointer_v<std::remove_cvref_t<Code>>) {
code_view = _code ? std::string_view(_code) : std::string_view{};
} else {
code_view = std::string_view(std::forward<Code>(_code));
}
return Unexpected<Error>(Error(std::move(_what), _kind, code_view));
}

/// Shorthand for a classified unexpected error at a nested path with a
/// machine-readable code.
template <class Code>
requires(std::convertible_to<Code, std::string_view> &&
!std::is_null_pointer_v<std::remove_cvref_t<Code>>)
inline Unexpected<Error> error(std::string _what, const ErrorKind _kind,
std::vector<ErrorDetail::PathSegment> _path,
Code&& _code) {
std::string_view code_view;
if constexpr (std::is_pointer_v<std::remove_cvref_t<Code>>) {
code_view = _code ? std::string_view(_code) : std::string_view{};
} else {
code_view = std::string_view(std::forward<Code>(_code));
}
if (_path.empty()) {
return Unexpected<Error>(Error(std::move(_what), _kind, code_view));
}
std::vector<ErrorDetail> details;
details.push_back(ErrorDetail{
.path = std::move(_path),
.message = _what,
.kind = _kind,
.code = std::string(code_view),
});
return Unexpected<Error>(Error(std::move(_what), std::move(details)));
}

} // namespace rfl

#ifdef REFLECTCPP_USE_STD_EXPECTED
Expand Down
5 changes: 4 additions & 1 deletion include/rfl/Size.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include "Ref.hpp"
#include "Result.hpp"
#include "internal/validator_code.hpp"
#include "parsing/schema/ValidationType.hpp"

namespace rfl {
Expand All @@ -22,7 +23,9 @@ struct Size {
static rfl::Result<T> 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<V>(
std::move(res).error(), "Size validation failed: ", "size.",
internal::BuiltinErrorCode::size, internal::compose_size_code));
}
return std::move(_t);
}
Expand Down
15 changes: 11 additions & 4 deletions include/rfl/Validator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "AllOf.hpp"
#include "Result.hpp"
#include "internal/HasValidation.hpp"
#include "internal/validator_code.hpp"

namespace rfl {

Expand All @@ -35,10 +36,12 @@ struct Validator {
try {
return wrap_validated(ValidationType::validate(_value));
} catch (const std::exception& e) {
return error(e.what(), ErrorKind::constraint_violation);
return error(e.what(), ErrorKind::constraint_violation,
internal::validator_code<ValidationType>());
} catch (...) {
return error("Unknown exception during validation.",
ErrorKind::constraint_violation);
ErrorKind::constraint_violation,
internal::validator_code<ValidationType>());
}
}

Expand All @@ -50,10 +53,12 @@ struct Validator {
try {
return wrap_validated(ValidationType::validate(std::move(_value)));
} catch (const std::exception& e) {
return error(e.what(), ErrorKind::constraint_violation);
return error(e.what(), ErrorKind::constraint_violation,
internal::validator_code<ValidationType>());
} catch (...) {
return error("Unknown exception during validation.",
ErrorKind::constraint_violation);
ErrorKind::constraint_violation,
internal::validator_code<ValidationType>());
}
}

Expand Down Expand Up @@ -208,6 +213,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<ValidationType>());
return error(std::move(err));
}
return Validator(AlreadyValidated{}, std::move(*_res));
Expand Down
42 changes: 30 additions & 12 deletions include/rfl/comparisons.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,11 @@ struct EqualTo {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value != threshold) {
return error(internal::comparison_error_message(
"Value expected to be equal to ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected to be equal to ", threshold,
_value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::equal_to));
}
return _value;
}
Expand Down Expand Up @@ -101,8 +104,11 @@ struct Minimum {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value < threshold) {
return error(internal::comparison_error_message(
"Value expected to be greater than or equal to ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected to be greater than or equal to ",
threshold, _value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::minimum));
}
return _value;
}
Expand Down Expand Up @@ -138,8 +144,11 @@ struct ExclusiveMinimum {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value <= threshold) {
return error(internal::comparison_error_message(
"Value expected to be greater than ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected to be greater than ", threshold,
_value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::exclusive_minimum));
}
return _value;
}
Expand Down Expand Up @@ -175,8 +184,11 @@ struct Maximum {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value > threshold) {
return error(internal::comparison_error_message(
"Value expected to be less than or equal to ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected to be less than or equal to ",
threshold, _value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::maximum));
}
return _value;
}
Expand Down Expand Up @@ -211,8 +223,11 @@ struct ExclusiveMaximum {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value >= threshold) {
return error(internal::comparison_error_message(
"Value expected to be less than ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected to be less than ", threshold,
_value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::exclusive_maximum));
}
return _value;
}
Expand Down Expand Up @@ -247,8 +262,11 @@ struct NotEqualTo {
static Result<T> validate(T _value) noexcept {
constexpr auto threshold = static_cast<T>(_threshold);
if (_value == threshold) {
return error(internal::comparison_error_message(
"Value expected not to be equal to ", threshold, _value));
return error(Error(internal::comparison_error_message(
"Value expected not to be equal to ", threshold,
_value),
ErrorKind::constraint_violation,
internal::BuiltinErrorCode::not_equal_to));
}
return _value;
}
Expand Down
Loading
Loading