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
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 @@ -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`.

Expand All @@ -195,9 +199,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 @@ -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("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
14 changes: 9 additions & 5 deletions include/rfl/AllOf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <vector>

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

namespace rfl {
Expand Down Expand Up @@ -33,13 +34,16 @@ struct AllOf {
private:
template <class T, class Head, class... Tail>
static rfl::Result<T> 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<Head>());
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<T, Tail...>(std::move(*res));
}
}
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
35 changes: 14 additions & 21 deletions include/rfl/OneOf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,20 @@ struct OneOf {
template <class T, class Head, class... Tail>
static rfl::Result<T> validate_impl(const T& _value,
std::vector<Error> _errors) {
return Head::validate(_value)
.and_then([&](auto&&) -> rfl::Result<T> {
if constexpr (sizeof...(Tail) == 0) {
if (_errors.size() == sizeof...(Cs)) {
return _value;
// The AI suggests return std::forward<decltype(_result)>(_result);
// is it correct in this context?
}
return error(make_error_message(_errors));
} else {
return validate_impl<T, Tail...>(_value, std::move(_errors));
}
})
.or_else([&](auto&& _err) -> rfl::Result<T> {
_errors.emplace_back(std::move(_err));
if constexpr (sizeof...(Tail) == 0) {
return error(make_error_message(_errors));
} else {
return validate_impl<T, Tail...>(_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<T, Tail...>(_value, std::move(_errors));
}
}
};

Expand Down
3 changes: 2 additions & 1 deletion include/rfl/PatternValidator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

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
9 changes: 7 additions & 2 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,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<ValidationType>());
}
}

Expand All @@ -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<ValidationType>());
}
}

Expand Down Expand Up @@ -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<ValidationType>());
return error(std::move(err));
}
return Validator(AlreadyValidated{}, std::move(*_res));
Expand Down
18 changes: 12 additions & 6 deletions include/rfl/comparisons.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
Loading
Loading