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
29 changes: 28 additions & 1 deletion docs/content/result.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,29 @@ struct ErrorDetail {

// The message, without the "Failed to parse field '...': " prefixes.
std::string message;

// Coarse, format-agnostic category of this failure.
rfl::ErrorKind kind = rfl::ErrorKind::other;

bool operator==(const ErrorDetail&) const = default;
};
```

`rfl::ErrorKind` (`enum class ErrorKind : std::uint8_t`) classifies input and I/O failures across formats without requiring callers to parse error message strings. It is an open enum (new enumerators may be added in minor releases; `switch` statements should include a `default:` branch):

- `rfl::ErrorKind::other` – unclassified error (custom parsers/reflectors, caller bugs, or formats not yet tagged; default for plain-string `rfl::Error`).
- `rfl::ErrorKind::io_error` – input could not be obtained or output could not be emitted (file open/read/write/close or stream I/O failure).
- `rfl::ErrorKind::syntax_error` – malformed input syntax (for example invalid JSON).
- `rfl::ErrorKind::missing_field` – a declared, individually-required slot has no entry (required struct field, tuple element, or tagged-union discriminator).
- `rfl::ErrorKind::unknown_field` – an undeclared or ambiguous key/field was encountered (for example under `rfl::NoExtraFields`).
- `rfl::ErrorKind::duplicate_field` – a non-repeatable key or field appeared more than once.
- `rfl::ErrorKind::invalid_length` – element or value count violated a bound fixed by the C++ type or option arity (for example `std::array<T, N>` size mismatch, tuple overflow, or `inplace_vector` capacity).
- `rfl::ErrorKind::invalid_type` – the node's native wire or structural type was incompatible with the target type (for example a string where an integer was expected, or an array where an object was expected).
- `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`.

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

```cpp
Expand All @@ -174,8 +194,10 @@ 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,
// message = "Size validation failed: ..."
// Second iteration: path = {"files", 1, "outputFile"},
// kind = rfl::ErrorKind::missing_field,
// message = "Field named 'outputFile' not found."
}
```
Expand All @@ -184,7 +206,12 @@ 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"))`.
`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):

```cpp
rfl::error("Port out of range", rfl::ErrorKind::invalid_value);
rfl::error("Port out of range", rfl::ErrorKind::invalid_value, {"port"});
```

## `.or_else(...)`, `.transform_error(...)`

Expand Down
6 changes: 4 additions & 2 deletions include/rfl/Generic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,15 +159,17 @@ class RFL_API Generic {
if (auto* ptr = std::get_if<Array>(&value_)) return *ptr;
return error(
"rfl::Generic: Could not cast the underlying value to an "
"rfl::Generic::Array.");
"rfl::Generic::Array.",
ErrorKind::invalid_type);
}

/// Casts the underlying value to a boolean or returns an rfl::Error, if the
/// underlying value is not a boolean.
Result<bool> to_bool() const noexcept {
if (auto* ptr = std::get_if<bool>(&value_)) return *ptr;
return error(
"rfl::Generic: Could not cast the underlying value to a boolean.");
"rfl::Generic: Could not cast the underlying value to a boolean.",
ErrorKind::invalid_type);
}

/// Casts the underlying value to a double or returns an rfl::Error, if the
Expand Down
7 changes: 5 additions & 2 deletions include/rfl/Literal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ class Literal {
/// range
static Result<Literal<fields_...>> from_value(ValueType _value) {
if (_value >= num_fields_) {
return error("Value cannot exceed number of fields.");
return error("Value cannot exceed number of fields.",
ErrorKind::invalid_value);
}
return Literal<fields_...>(_value);
}
Expand Down Expand Up @@ -375,7 +376,9 @@ class Literal {
if (!found) {
return error(
"Literal does not support string '" + _str +
"'. The following strings are supported: " + allowed_strings() + ".");
"'. The following strings are supported: " + allowed_strings() +
".",
ErrorKind::invalid_value);
}
return idx;
}
Expand Down
3 changes: 2 additions & 1 deletion include/rfl/Object.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ class Object {
Result<T> get(const std::string& _key) const noexcept {
const auto i = find(_key);
if (i == size()) {
return error("Key named '" + _key + "' not found.");
return error("Key named '" + _key + "' not found.",
ErrorKind::missing_field);
}
return data_[i].second;
}
Expand Down
28 changes: 28 additions & 0 deletions include/rfl/Result.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace rfl {

using Error = rfl::internal::Error;
using ErrorDetail = rfl::internal::ErrorDetail;
using ErrorKind = rfl::internal::ErrorKind;

/// To be returned when there is nothing to return, but there might be an error.
struct Nothing {};
Expand Down Expand Up @@ -56,6 +57,33 @@ inline Unexpected<Error> error(Error&& _err) {
return Unexpected<Error>(std::move(_err));
}

/// Shorthand for a classified unexpected error (leaf error, no detail
/// allocation).
inline Unexpected<Error> error(const std::string& _what,
const ErrorKind _kind) {
return Unexpected<Error>(Error(_what, _kind));
}

inline Unexpected<Error> error(std::string&& _what, const ErrorKind _kind) {
return Unexpected<Error>(Error(std::move(_what), _kind));
}

/// Shorthand for a classified unexpected error at a nested path. Allocates
/// explicit details only when _path is non-empty.
inline Unexpected<Error> error(std::string _what, const ErrorKind _kind,
std::vector<ErrorDetail::PathSegment> _path) {
if (_path.empty()) {
return Unexpected<Error>(Error(std::move(_what), _kind));
}
std::vector<ErrorDetail> details;
details.push_back(ErrorDetail{
.path = std::move(_path),
.message = _what,
.kind = _kind,
});
return Unexpected<Error>(Error(std::move(_what), std::move(details)));
}

} // namespace rfl

#ifdef REFLECTCPP_USE_STD_EXPECTED
Expand Down
9 changes: 7 additions & 2 deletions include/rfl/Timestamp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,23 @@ class Timestamp {
try {
return Timestamp(_str);
} catch (std::exception& e) {
return error(e.what());
return error(e.what(), ErrorKind::invalid_value);
}
}

/// Returns a result containing the timestamp when successful or an Error otherwise.
/// This is an alternative to the throwing constructor for error handling without exceptions.
/// @param _str The string to parse in the format specified by the template parameter
/// @return Result containing the Timestamp if parsing succeeded, or an error otherwise
static Result<Timestamp> from_string(const std::string& _str) {
static Result<Timestamp> from_string(const std::string& _str) noexcept {
return from_string(_str.c_str());
}

/// Exception-free reflection hook for parsers.
static Result<Timestamp> from_reflection(const std::string& _str) noexcept {
return from_string(_str);
}

/// Generic factory method for creating a Timestamp from a string.
/// Returns a result containing the timestamp when successful or an Error otherwise.
/// @param _str The string to parse (can be const char* or std::string)
Expand Down
12 changes: 8 additions & 4 deletions include/rfl/Validator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ struct Validator {
try {
return wrap_validated(ValidationType::validate(_value));
} catch (std::exception& e) {
return error(e.what());
return error(e.what(), ErrorKind::constraint_violation);
}
}

Expand All @@ -47,7 +47,7 @@ struct Validator {
try {
return wrap_validated(ValidationType::validate(std::move(_value)));
} catch (std::exception& e) {
return error(e.what());
return error(e.what(), ErrorKind::constraint_violation);
}
}

Expand Down Expand Up @@ -199,8 +199,12 @@ struct Validator {

/// Wraps the result of a validation without throwing if it failed.
static Result<Validator> wrap_validated(Result<T>&& _res) {
return std::move(_res).transform(
[](T&& _v) { return Validator(AlreadyValidated{}, std::move(_v)); });
if (!_res) {
Error err = std::move(_res).error();
internal::set_error_kind_if_other(err, ErrorKind::constraint_violation);
return error(std::move(err));
}
return Validator(AlreadyValidated{}, std::move(*_res));
}

private:
Expand Down
2 changes: 1 addition & 1 deletion include/rfl/enums.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Result<EnumType> string_to_enum(const std::string& _str) {
sep = ", ";
}
msg += "].";
return error(msg);
return error(std::move(msg), ErrorKind::invalid_value);
};

const auto cast_numbers_or_names =
Expand Down
14 changes: 9 additions & 5 deletions include/rfl/env/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ rfl::Result<T> parse_value(const std::string& _str,
if (_str == "false" || _str == "0") {
return false;
}
return error("Could not cast '" + _str + "' to boolean for key '" + _path +
"'.");
return error(
"Could not cast '" + _str + "' to boolean for key '" + _path + "'.",
ErrorKind::invalid_value);
}

/// Parses a string value to a floating-point number.
Expand Down Expand Up @@ -106,7 +107,8 @@ rfl::Result<T> parse_value(const std::string& _str,
#endif
if (end != _str.c_str() + _str.size()) {
return error("Could not cast '" + _str + "' to floating point for key '" +
_path + "'.");
_path + "'.",
ErrorKind::invalid_value);
}
return static_cast<T>(value);
}
Expand All @@ -126,7 +128,8 @@ rfl::Result<T> parse_value(const std::string& _str,
std::from_chars(_str.data(), _str.data() + _str.size(), value);
if (ec != std::errc() || ptr != _str.data() + _str.size()) {
return error("Could not cast '" + _str + "' to integer for key '" + _path +
"'.");
"'.",
ErrorKind::invalid_value);
}
return value;
}
Expand Down Expand Up @@ -270,7 +273,8 @@ struct Reader {
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
const auto str = get_value(_var);
if (!str) {
return error("No value for key '" + _var.path + "'.");
return error("No value for key '" + _var.path + "'.",
ErrorKind::missing_field);
}
return parse_value<T>(*str, _var.path);
}
Expand Down
3 changes: 2 additions & 1 deletion include/rfl/generic/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ struct Reader {
rfl::Result<InputVarType> get_field_from_array(
const size_t _idx, const InputArrayType& _arr) const noexcept {
if (_idx >= _arr.size()) {
return error("Index " + std::to_string(_idx) + " of of bounds.");
return error("Index " + std::to_string(_idx) + " of of bounds.",
ErrorKind::missing_field);
}
return _arr[_idx];
}
Expand Down
Loading