diff --git a/docs/content/result.md b/docs/content/result.md index fb59c2280..a1b6af6fa 100644 --- a/docs/content/result.md +++ b/docs/content/result.md @@ -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` 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 @@ -174,8 +194,10 @@ const auto result = rfl::json::read( 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." } ``` @@ -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 message"))`. +`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): + +```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(...)` diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index 46f79f65f..7a783efb0 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -159,7 +159,8 @@ class RFL_API Generic { if (auto* ptr = std::get_if(&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 @@ -167,7 +168,8 @@ class RFL_API Generic { Result to_bool() const noexcept { if (auto* ptr = std::get_if(&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 diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 4208d7713..0ea7ebc61 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -99,7 +99,8 @@ class Literal { /// range static Result> 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(_value); } @@ -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; } diff --git a/include/rfl/Object.hpp b/include/rfl/Object.hpp index 7c36cb5b0..c82d373bd 100644 --- a/include/rfl/Object.hpp +++ b/include/rfl/Object.hpp @@ -285,7 +285,8 @@ class Object { Result 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; } diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 08d01fc1f..104bf0d8f 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -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 {}; @@ -56,6 +57,33 @@ inline Unexpected error(Error&& _err) { return Unexpected(std::move(_err)); } +/// Shorthand for a classified unexpected error (leaf error, no detail +/// allocation). +inline Unexpected error(const std::string& _what, + const ErrorKind _kind) { + return Unexpected(Error(_what, _kind)); +} + +inline Unexpected error(std::string&& _what, const ErrorKind _kind) { + return Unexpected(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(std::string _what, const ErrorKind _kind, + std::vector _path) { + if (_path.empty()) { + return Unexpected(Error(std::move(_what), _kind)); + } + std::vector details; + details.push_back(ErrorDetail{ + .path = std::move(_path), + .message = _what, + .kind = _kind, + }); + return Unexpected(Error(std::move(_what), std::move(details))); +} + } // namespace rfl #ifdef REFLECTCPP_USE_STD_EXPECTED diff --git a/include/rfl/Timestamp.hpp b/include/rfl/Timestamp.hpp index a940e0fcb..da71c7828 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -74,7 +74,7 @@ class Timestamp { try { return Timestamp(_str); } catch (std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::invalid_value); } } @@ -82,10 +82,15 @@ class Timestamp { /// 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 from_string(const std::string& _str) { + static Result from_string(const std::string& _str) noexcept { return from_string(_str.c_str()); } + /// Exception-free reflection hook for parsers. + static Result 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) diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 9be58bf61..1d9373b63 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -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); } } @@ -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); } } @@ -199,8 +199,12 @@ struct Validator { /// Wraps the result of a validation without throwing if it failed. static Result wrap_validated(Result&& _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: diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..13f30b1e7 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -101,7 +101,7 @@ Result 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 = diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..cf121894d 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -75,8 +75,9 @@ rfl::Result 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. @@ -106,7 +107,8 @@ rfl::Result 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(value); } @@ -126,7 +128,8 @@ rfl::Result 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; } @@ -270,7 +273,8 @@ struct Reader { rfl::Result 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(*str, _var.path); } diff --git a/include/rfl/generic/Reader.hpp b/include/rfl/generic/Reader.hpp index db9631800..b5f9b8dd2 100644 --- a/include/rfl/generic/Reader.hpp +++ b/include/rfl/generic/Reader.hpp @@ -30,7 +30,8 @@ struct Reader { rfl::Result 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]; } diff --git a/include/rfl/internal/Error.hpp b/include/rfl/internal/Error.hpp index f8797c1f0..11a5f58af 100644 --- a/include/rfl/internal/Error.hpp +++ b/include/rfl/internal/Error.hpp @@ -2,6 +2,7 @@ #define RFL_INTERNAL_ERROR_HPP_ #include +#include #include #include #include @@ -12,6 +13,59 @@ namespace rfl::internal { +/// Coarse, format-agnostic classification of an ErrorDetail failure. +/// Classifies the input (or I/O environment), never caller/programmer bugs. +/// Open enum: new enumerators may be added in minor releases; switch +/// statements over ErrorKind should include a `default:` branch. +enum class ErrorKind : std::uint8_t { + /// Unclassified: custom parsers/reflectors, caller/programmer bugs, + /// and formats not yet tagged. + other = 0, + + /// Input could not be obtained or output could not be emitted + /// (file open/read/write/close, stream badbit/failbit, directory/size I/O). + io_error, + + /// Bytes or tokens cannot form the format's data model regardless of target + /// type (malformed/truncated JSON/YAML/TOML, invalid UTF-8/UTF-16, depth + /// limit, recursive YAML alias, malformed CLI token such as `--=val`). + syntax_error, + + /// A declared, individually-required slot has no entry + /// (required struct field, tuple element, required positional, or + /// tagged-union discriminator key). + missing_field, + + /// A key, option, or argv token resolves to no declared slot—or ambiguously + /// to more than one (under NoExtraFields, extra CLI positionals, or + /// ambiguous CLI option abbreviations). + unknown_field, + + /// A key or non-repeatable option appeared more than once where repeats + /// are forbidden (e.g. duplicate mapping key or scalar option). + duplicate_field, + + /// Element or value count violates a count fixed by the C++ type or option + /// arity (std::array size mismatch, tuple overflow, inplace_vector + /// capacity, CLI option arity mismatch). + invalid_length, + + /// The node's native wire class is incompatible with the target type + /// (null/bool/integer/float/string/bytes/array/object mismatch). + invalid_type, + + /// Right wire class (or string-only format token), but domain/lexical + /// conversion to the C++ type failed (numeric range/sign overflow including + /// negative int for unsigned, unknown enum/tag/FieldVariant key, bad + /// timestamp/base64/bitset, no matching variant). + invalid_value, + + /// Value successfully converted to the target C++ type, then a declared + /// check rejected it (rfl::Validator<...>, AllOf/AnyOf/OneOf, Size, Pattern, + /// Minimum, CLI constraints). + constraint_violation, +}; + /// Describes a single failure contained in an Error: where it occurred and /// what went wrong. struct ErrorDetail { @@ -28,6 +82,9 @@ struct ErrorDetail { /// '...': " prefixes that Error::what() contains for every level of nesting. std::string message; + /// The coarse category of this failure. + ErrorKind kind = ErrorKind::other; + bool operator==(const ErrorDetail&) const = default; }; @@ -46,6 +103,20 @@ class Error { /// @param _what The error message describing what went wrong (will be moved) Error(std::string&& _what) : what_(std::move(_what)) {} + /// Constructs a classified leaf error with a message (copy), without + /// allocating an explicit detail vector. + /// @param _what The error message describing what went wrong + /// @param _kind Coarse classification of the failure + Error(const std::string& _what, const ErrorKind _kind) + : what_(_what), kind_(_kind) {} + + /// Constructs a classified leaf error with a message (move), without + /// allocating an explicit detail vector. + /// @param _what The error message describing what went wrong (will be moved) + /// @param _kind Coarse classification of the failure + Error(std::string&& _what, const ErrorKind _kind) + : what_(std::move(_what)), kind_(_kind) {} + /// Constructs an error with a message and the individual failures it /// summarizes. /// @param _what The error message describing what went wrong @@ -53,7 +124,9 @@ class Error { Error(std::string _what, std::vector _details) : what_(std::move(_what)), details_(_details.empty() ? OptionalDetails() - : OptionalDetails(std::move(_details))) {} + : OptionalDetails(std::move(_details))), + kind_(details_.has_value() ? (*details_).front().kind + : ErrorKind::other) {} /// Destructor. ~Error() = default; @@ -82,12 +155,20 @@ class Error { /// from state std::string what() && { return std::move(what_); } + /// Returns the ErrorKind of this error. For multi-error results, returns the + /// kind of the first detail. + ErrorKind kind() const noexcept { + return details_.has_value() && !(*details_).empty() + ? (*details_).front().kind + : kind_; + } + /// 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_}}; + return {ErrorDetail{.path = {}, .message = what_, .kind = kind_}}; } return *details_; } @@ -96,12 +177,35 @@ class Error { /// moved from state. std::vector details() && { if (!details_.has_value()) { - return {ErrorDetail{.path = {}, .message = std::move(what_)}}; + return { + ErrorDetail{.path = {}, .message = std::move(what_), .kind = kind_}}; } return std::move(*details_); } private: + friend bool has_allocated_details(const Error& _err) noexcept { + return _err.details_.has_value(); + } + + friend void set_error_kind_if_other(Error& _err, + const ErrorKind _kind) noexcept { + if (_kind == ErrorKind::other) { + return; + } + if (!_err.details_.has_value()) { + if (_err.kind_ == ErrorKind::other) { + _err.kind_ = _kind; + } + return; + } + for (auto& detail : *_err.details_) { + if (detail.kind == ErrorKind::other) { + detail.kind = _kind; + } + } + } + /// 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. @@ -162,8 +266,18 @@ class Error { /// The individual failures summarized by what_. Holds nothing, unless what_ /// was assembled from failures at nested locations. OptionalDetails details_; + + /// Coarse category for a leaf error when details_ holds nothing. + ErrorKind kind_ = ErrorKind::other; }; +/// Returns whether _err has a heap-allocated detail vector. +bool has_allocated_details(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; + } // namespace rfl::internal #endif diff --git a/include/rfl/internal/HasFromReflectionMethod.hpp b/include/rfl/internal/HasFromReflectionMethod.hpp index 8c794cf06..5c34e6387 100644 --- a/include/rfl/internal/HasFromReflectionMethod.hpp +++ b/include/rfl/internal/HasFromReflectionMethod.hpp @@ -4,13 +4,19 @@ #include #include +#include "../Result.hpp" + namespace rfl::internal { -/// Satisfied by a type `T` providing `static T from_reflection(ReflectionType&&)`. +/// Satisfied by a type `T` providing `static U from_reflection(ReflectionType&&)` +/// where `U` is convertible to `T` or `Result`. template -concept HasFromReflectionMethod = requires(typename T::ReflectionType&& _r) { - { T::from_reflection(std::move(_r)) } -> std::convertible_to; -}; +concept HasFromReflectionMethod = + requires(typename T::ReflectionType&& _r) { + { T::from_reflection(std::move(_r)) } -> std::convertible_to; + } || requires(typename T::ReflectionType&& _r) { + { T::from_reflection(std::move(_r)) } -> std::convertible_to>; + }; } // namespace rfl::internal diff --git a/include/rfl/internal/base64.hpp b/include/rfl/internal/base64.hpp index 6a18fc2e9..e166b3500 100644 --- a/include/rfl/internal/base64.hpp +++ b/include/rfl/internal/base64.hpp @@ -45,7 +45,7 @@ inline Result decode_base64(const std::string_view _encoded) { const auto padding = _encoded.size() - size; if (size % 4 == 1 || padding > 2 || (padding != 0 && _encoded.size() % 4 != 0)) { - return error("Invalid Base64 length or padding."); + return error("Invalid Base64 length or padding.", ErrorKind::invalid_value); } Bytestring decoded; @@ -66,7 +66,8 @@ inline Result decode_base64(const std::string_view _encoded) { } else if (c == '/' || c == '_') { value = 63; } else { - return error("Invalid character in Base64 string."); + return error("Invalid character in Base64 string.", + ErrorKind::invalid_value); } buffer = (buffer << 6) | value; bits += 6; diff --git a/include/rfl/internal/bitset.hpp b/include/rfl/internal/bitset.hpp index 2ed688361..c3ff1b9bc 100644 --- a/include/rfl/internal/bitset.hpp +++ b/include/rfl/internal/bitset.hpp @@ -19,12 +19,13 @@ Result> bitset_from_string(const std::string_view _str) { message += ", got "; message += std::to_string(_str.size()); message += "."; - return error(std::move(message)); + return error(std::move(message), ErrorKind::invalid_value); } std::bitset bits; for (std::size_t i = 0; i < N; ++i) { if (_str[i] != '0' && _str[i] != '1') { - return error("Bitset strings may contain only '0' and '1'."); + return error("Bitset strings may contain only '0' and '1'.", + ErrorKind::invalid_value); } bits[N - 1 - i] = _str[i] == '1'; } @@ -56,12 +57,13 @@ Result> bitset_from_bytes(const Bytes& _bytes) { message += " packed bitset bytes, got "; message += std::to_string(_bytes.size()); message += "."; - return error(std::move(message)); + return error(std::move(message), ErrorKind::invalid_value); } if constexpr (N % 8 != 0) { constexpr auto mask = (1u << (8 - N % 8)) - 1; if ((static_cast(_bytes.back()) & mask) != 0) { - return error("Packed bitset padding bits must be zero."); + return error("Packed bitset padding bits must be zero.", + ErrorKind::invalid_value); } } std::bitset bits; diff --git a/include/rfl/io/load_file.hpp b/include/rfl/io/load_file.hpp index c39214ded..eecc6c0bb 100644 --- a/include/rfl/io/load_file.hpp +++ b/include/rfl/io/load_file.hpp @@ -20,7 +20,8 @@ Result load_file(const std::string& _fname, try { std::ifstream input(_fname, _mode); if (!input.is_open()) { - return error("Unable to open file '" + _fname + "' for reading."); + return error("Unable to open file '" + _fname + "' for reading.", + ErrorKind::io_error); } Container bytes; std::error_code ec; @@ -29,21 +30,24 @@ Result load_file(const std::string& _fname, if (size > bytes.max_size() || size > static_cast( (std::numeric_limits::max)())) { - return error("File '" + _fname + "' is too large to read."); + return error("File '" + _fname + "' is too large to read.", + ErrorKind::io_error); } bytes.resize(static_cast(size)); if (!bytes.empty()) { input.read(bytes.data(), static_cast(bytes.size())); bytes.resize(static_cast(input.gcount())); if (input.bad() || (input.fail() && !input.eof())) { - return error("Unable to read file '" + _fname + "'."); + return error("Unable to read file '" + _fname + "'.", + ErrorKind::io_error); } if (input.eof()) { return bytes; } } } else if (std::filesystem::is_directory(_fname, ec)) { - return error("Cannot read directory '" + _fname + "' as a file."); + return error("Cannot read directory '" + _fname + "' as a file.", + ErrorKind::io_error); } // The size is only a hint: text conversion, growing files, and special // files can produce a different number of bytes. Never require seeking. @@ -51,13 +55,15 @@ Result load_file(const std::string& _fname, do { input.read(buffer.data(), static_cast(buffer.size())); if (input.bad() || (input.fail() && !input.eof())) { - return error("Unable to read file '" + _fname + "'."); + return error("Unable to read file '" + _fname + "'.", + ErrorKind::io_error); } bytes.insert(bytes.end(), buffer.data(), buffer.data() + input.gcount()); } while (!input.eof()); return bytes; } catch (const std::exception& e) { - return error("Unable to read file '" + _fname + "': " + e.what()); + return error("Unable to read file '" + _fname + "': " + e.what(), + ErrorKind::io_error); } } diff --git a/include/rfl/io/save_bytes.hpp b/include/rfl/io/save_bytes.hpp index a6c29b0e6..e55f37e18 100644 --- a/include/rfl/io/save_bytes.hpp +++ b/include/rfl/io/save_bytes.hpp @@ -15,15 +15,17 @@ Result save_bytes(const std::string& _fname, const T& _obj, try { std::ofstream output(_fname, std::ios::out | std::ios::binary); if (!output.is_open()) { - return error("Unable to open file '" + _fname + "' for writing."); + return error("Unable to open file '" + _fname + "' for writing.", + ErrorKind::io_error); } _write(_obj, output); output.close(); if (!output) { - return error("Unable to write or close file '" + _fname + "'."); + return error("Unable to write or close file '" + _fname + "'.", + ErrorKind::io_error); } } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::io_error); } return Nothing{}; } diff --git a/include/rfl/io/save_string.hpp b/include/rfl/io/save_string.hpp index 8d2abdb98..5b661512e 100644 --- a/include/rfl/io/save_string.hpp +++ b/include/rfl/io/save_string.hpp @@ -16,15 +16,17 @@ Result save_string(const std::string& _fname, const T& _obj, std::ofstream outfile; outfile.open(_fname); if (!outfile.is_open()) { - return error("Unable to open file '" + _fname + "' for writing."); + return error("Unable to open file '" + _fname + "' for writing.", + ErrorKind::io_error); } _write(_obj, outfile); outfile.close(); if (!outfile) { - return error("Unable to write or close file '" + _fname + "'."); + return error("Unable to write or close file '" + _fname + "'.", + ErrorKind::io_error); } } catch (const std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::io_error); } return Nothing{}; } diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index fe4c576b3..c6102dbee 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -68,7 +68,8 @@ struct Reader { const size_t _idx, const InputArrayType _arr) const noexcept { const auto var = InputVarType(yyjson_arr_get(_arr.val_, _idx)); if (!var.val_) { - return error("Index " + std::to_string(_idx) + " of of bounds."); + return error("Index " + std::to_string(_idx) + " of of bounds.", + ErrorKind::missing_field); } return var; } @@ -81,7 +82,8 @@ struct Reader { const std::string& _name, const InputObjectType _obj) const noexcept { const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str())); if (!var.val_) { - return error("Object contains no field named '" + _name + "'."); + return error("Object contains no field named '" + _name + "'.", + ErrorKind::missing_field); } return var; } @@ -150,48 +152,54 @@ struct Reader { if constexpr (std::is_same, std::string>()) { const auto r = yyjson_get_str(_var.val_); if (r == NULL) { - return error("Could not cast to string."); + return error("Could not cast to string.", ErrorKind::invalid_type); } return std::string(r, yyjson_get_len(_var.val_)); } else if constexpr (std::is_same, Bytestring>()) { const auto str = yyjson_get_str(_var.val_); if (str == nullptr) { - return error("Could not cast to a Base64 string."); + return error("Could not cast to a Base64 string.", + ErrorKind::invalid_type); } return internal::decode_base64( std::string_view(str, yyjson_get_len(_var.val_))); } else if constexpr (std::is_same, bool>()) { if (!yyjson_is_bool(_var.val_)) { - return error("Could not cast to boolean."); + return error("Could not cast to boolean.", ErrorKind::invalid_type); } return yyjson_get_bool(_var.val_); } else if constexpr (std::is_floating_point>()) { if (!yyjson_is_num(_var.val_)) { - return error("Could not cast to double."); + return error("Could not cast to double.", ErrorKind::invalid_type); } return static_cast(yyjson_get_num(_var.val_)); } else if constexpr (std::is_unsigned>()) { if (!yyjson_is_uint(_var.val_)) { - return error("Could not cast to uint."); + if (yyjson_is_sint(_var.val_)) { + return error("Could not cast to uint.", ErrorKind::invalid_value); + } + return error("Could not cast to uint.", ErrorKind::invalid_type); } const auto value = yyjson_get_uint(_var.val_); if (value > static_cast(std::numeric_limits>::max())) { - return error("Integer is out of range for the target type."); + return error("Integer is out of range for the target type.", + ErrorKind::invalid_value); } return static_cast(value); } else if constexpr (std::is_integral>()) { if (!yyjson_is_int(_var.val_)) { - return error("Could not cast to int."); + return error("Could not cast to int.", ErrorKind::invalid_type); } const auto value = yyjson_get_sint(_var.val_); if (value < std::numeric_limits>::min() || value > std::numeric_limits>::max()) { - return error("Integer is out of range for the target type."); + return error("Integer is out of range for the target type.", + ErrorKind::invalid_value); } return static_cast(value); @@ -205,7 +213,7 @@ struct Reader { /// @return Result containing the array, or an error if value is not an array rfl::Result to_array(const InputVarType _var) const noexcept { if (!yyjson_is_arr(_var.val_)) { - return error("Could not cast to array!"); + return error("Could not cast to array!", ErrorKind::invalid_type); } return InputArrayType(_var.val_); } @@ -216,7 +224,7 @@ struct Reader { rfl::Result to_object( const InputVarType _var) const noexcept { if (!yyjson_is_obj(_var.val_)) { - return error("Could not cast to object!"); + return error("Could not cast to object!", ErrorKind::invalid_type); } return InputObjectType(_var.val_); } diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index ad3e47b1e..ebdb8a46d 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -52,7 +52,8 @@ Result> read( yyjson_doc* doc = yyjson_read_opts(const_cast(_json_str.data()), _json_str.size(), _flag, NULL, &err); if (!doc) { - return error("Could not parse document: " + std::string(err.msg)); + return error("Could not parse document: " + std::string(err.msg), + ErrorKind::syntax_error); } yyjson_val* root = yyjson_doc_get_root(doc); const auto r = Reader(); diff --git a/include/rfl/parsing/ArrayReader.hpp b/include/rfl/parsing/ArrayReader.hpp index eb600ee5a..317feb47d 100644 --- a/include/rfl/parsing/ArrayReader.hpp +++ b/include/rfl/parsing/ArrayReader.hpp @@ -37,7 +37,8 @@ class ArrayReader { std::optional check_size() const { if (num_set_ != size_) { return Error("Expected " + std::to_string(size_) + " elements, got " + - std::to_string(num_set_) + "."); + std::to_string(num_set_) + ".", + ErrorKind::invalid_length); } return std::nullopt; } @@ -56,8 +57,9 @@ class ArrayReader { std::optional read(const InputVarType& _var) const { if (num_set_ == size_) { return Error("Expected " + std::to_string(size_) + - " elements, got at least " + std::to_string(size_ + 1) + - "."); + " elements, got at least " + std::to_string(size_ + 1) + + ".", + ErrorKind::invalid_length); } auto res = Parser, ProcessorsType>::read(*r_, _var); diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 7e586b749..86e40edbd 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -55,7 +55,8 @@ struct FieldVariantParser { if (!field_variant) { return error( "Could not parse: Expected the object to have " - "exactly one field, but found none."); + "exactly one field, but found none.", + ErrorKind::invalid_value); } return std::move(*field_variant); }; diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index b7454b1a7..3ebf8a9fe 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -12,6 +12,7 @@ #include "../internal/is_array.hpp" #include "../internal/nth_element_t.hpp" #include "Parser_base.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -46,7 +47,8 @@ class FieldVariantReader { if (*field_variant_) { *field_variant_ = error( "Could not parse rfl::Variant: Expected the object to have " - "exactly one field, but found more than one."); + "exactly one field, but found more than one.", + ErrorKind::invalid_value); return; } try_matching_fields( @@ -57,7 +59,7 @@ class FieldVariantReader { stream << "Could not parse rfl::Variant, could not match field named " "'" << _disc_value << "'."; - *field_variant_ = error(stream.str()); + *field_variant_ = error(stream.str(), ErrorKind::invalid_value); } } @@ -80,11 +82,12 @@ class FieldVariantReader { const auto to_variant = [](ValueType&& _val) { return rfl::Variant(FieldType(std::move(_val))); }; - const auto embellish_error = [&](const Error& _e) { + const auto embellish_error = [&](Error _e) { std::stringstream stream; stream << "Could not parse rfl::Variant with field '" - << std::string(_disc_value) << "': " << _e.what(); - return Error(stream.str()); + << std::string(_disc_value) << "': "; + return wrap_error(stream.str(), std::string(_disc_value), + std::move(_e)); }; *field_variant_ = Parser::read(*r_, _var) .transform(to_variant) diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index fe1e8ffdc..c98ca1022 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -10,6 +10,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_validator.hpp" #include "Parser_base.hpp" #include "wrap_error.hpp" @@ -66,7 +67,7 @@ class MapReader { static_assert(always_false_v, "Unsupported type"); } } catch (std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::invalid_value); } } @@ -80,7 +81,11 @@ class MapReader { return std::make_pair(KeyType(std::forward(_key)), std::move(_pair.second)); } catch (std::exception& e) { - return error(e.what()); + if constexpr (internal::is_validator_v) { + return error(e.what(), ErrorKind::constraint_violation); + } else { + return error(e.what(), ErrorKind::invalid_value); + } } }; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..2e72716dd 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -378,7 +378,8 @@ struct NamedTupleParser { "Field named '" + std::string(current_name) + "' not found, and its default value could not be " "constructed: " + - e.what())); + e.what(), + ErrorKind::missing_field)); return; } std::get<_i>(*_set) = true; @@ -394,8 +395,8 @@ struct NamedTupleParser { std::stringstream stream; stream << "Field named '" << std::string(current_name) << "' not found."; - _errors->emplace_back( - make_nested_error(std::string(current_name), stream.str())); + _errors->emplace_back(make_nested_error( + std::string(current_name), stream.str(), ErrorKind::missing_field)); return; } @@ -420,7 +421,8 @@ struct NamedTupleParser { "Field named '" + std::string(current_name) + "' not found, and its default value could not be " "constructed: " + - e.what())); + e.what(), + ErrorKind::missing_field)); return; } } diff --git a/include/rfl/parsing/ParserDuration.hpp b/include/rfl/parsing/ParserDuration.hpp index cc02e91c4..15b3a62d4 100644 --- a/include/rfl/parsing/ParserDuration.hpp +++ b/include/rfl/parsing/ParserDuration.hpp @@ -138,7 +138,7 @@ struct ParserDuration { return SupportedTypes(std::chrono::years(_r.count)); default: - return error("Unsupported unit."); + return error("Unsupported unit.", ErrorKind::invalid_value); } } diff --git a/include/rfl/parsing/ParserRflVariant.hpp b/include/rfl/parsing/ParserRflVariant.hpp index 857aff132..5ffd61849 100644 --- a/include/rfl/parsing/ParserRflVariant.hpp +++ b/include/rfl/parsing/ParserRflVariant.hpp @@ -106,7 +106,8 @@ class ParserRflVariant, "Could not parse the variant. Each of the " "possible alternatives failed " "for the following reasons: ", - 100000)); + 100000), + ErrorKind::invalid_value); } } } diff --git a/include/rfl/parsing/ParserTaggedUnion.hpp b/include/rfl/parsing/ParserTaggedUnion.hpp index dee232752..dc1e23f03 100644 --- a/include/rfl/parsing/ParserTaggedUnion.hpp +++ b/include/rfl/parsing/ParserTaggedUnion.hpp @@ -158,7 +158,10 @@ struct ParserTaggedUnion, << _discriminator.str() << " '" << _disc_value << "'. The following tags are allowed: " << internal::strings::join(", ", names); - return error(stream.str()); + const ErrorDetail::PathSegment seg = + no_field_names_ ? ErrorDetail::PathSegment(size_t{0}) + : ErrorDetail::PathSegment(_discriminator.str()); + return error(stream.str(), ErrorKind::invalid_value, {seg}); } } @@ -213,11 +216,14 @@ struct ParserTaggedUnion, return _r.template to_basic_type(_var); }; - const auto embellish_error = [](const auto&) { + const auto embellish_error = [](const Error& _e) { std::stringstream stream; stream << "Could not parse tagged union: Could not find field '" << _discriminator.str() << "' or type of field was not a string."; - return Error(stream.str()); + const ErrorDetail::PathSegment seg = + no_field_names_ ? ErrorDetail::PathSegment(size_t{0}) + : ErrorDetail::PathSegment(_discriminator.str()); + return make_nested_error(seg, stream.str(), _e.kind()); }; if constexpr (no_field_names_) { diff --git a/include/rfl/parsing/ParserTimePoint.hpp b/include/rfl/parsing/ParserTimePoint.hpp index 558bb42b5..1e31889ee 100644 --- a/include/rfl/parsing/ParserTimePoint.hpp +++ b/include/rfl/parsing/ParserTimePoint.hpp @@ -118,7 +118,8 @@ struct ParserTimePoint { const char* str = _str.c_str(); const char* rest = parse_datetime(str, &tm); if (!rest) { - return error("Could not parse time point from '" + _str + "'."); + return error("Could not parse time point from '" + _str + "'.", + ErrorKind::invalid_value); } auto t = to_time_t(tm); @@ -152,17 +153,19 @@ struct ParserTimePoint { if (*rest == '+' || *rest == '-') { const auto offset = parse_tz_offset(rest); if (!offset) { - return error("Could not parse timezone offset from '" + _str + "'."); + return error("Could not parse timezone offset from '" + _str + "'.", + ErrorKind::invalid_value); } tp -= *offset; } else if (*rest != 'Z' && *rest != '\0') { return error("Could not parse time point from '" + _str + - "': expected 'Z', timezone offset, or end of string."); + "': expected 'Z', timezone offset, or end of string.", + ErrorKind::invalid_value); } return std::chrono::time_point_cast(tp); } catch (std::exception& e) { - return error(e.what()); + return error(e.what(), ErrorKind::invalid_value); } } diff --git a/include/rfl/parsing/ParserVariant.hpp b/include/rfl/parsing/ParserVariant.hpp index 6ea04ce5d..d70396300 100644 --- a/include/rfl/parsing/ParserVariant.hpp +++ b/include/rfl/parsing/ParserVariant.hpp @@ -127,7 +127,8 @@ class ParserVariant, ProcessorsType> { "Could not parse the variant. Each of the " "possible alternatives failed " "for the following reasons: ", - 100000)); + 100000), + ErrorKind::invalid_value); } } } diff --git a/include/rfl/parsing/ParserWString.hpp b/include/rfl/parsing/ParserWString.hpp index 9d6c7ef8e..e787c44a0 100644 --- a/include/rfl/parsing/ParserWString.hpp +++ b/include/rfl/parsing/ParserWString.hpp @@ -52,7 +52,8 @@ struct ParserWString { auto outStr = internal::strings::utf8_to_wstring(inStr.value()); if (!outStr) { return Result( - error("Could not parse the string: it is not valid UTF-8.")); + error("Could not parse the string: it is not valid UTF-8.", + ErrorKind::invalid_value)); } return Result(std::move(*outStr)); diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..ad5c309b5 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -248,7 +248,12 @@ struct Parser { try { using NT = decltype(_named_tuple); if constexpr (internal::HasFromReflectionMethod) { - return T::from_reflection(std::forward(_named_tuple)); + auto res = T::from_reflection(std::forward(_named_tuple)); + if constexpr (std::convertible_to>) { + return res; + } else { + return Result(T(std::move(res))); + } } else if constexpr (internal::is_literal_v) { // Unlike the constructor, from_string does not throw when the // string is not one of the literal's values. diff --git a/include/rfl/parsing/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index df127aa70..2f48543eb 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -66,7 +66,7 @@ class TupleReader { if (num_set_ == size_) { std::stringstream stream; stream << "Expected " << size_ << " fields, but got at least one more."; - return Error(stream.str()); + return Error(stream.str(), ErrorKind::invalid_length); } std::optional err; [&](std::integer_sequence) { @@ -96,7 +96,8 @@ class TupleReader { is_required()) { *_err = make_nested_error( static_cast(_i), - "Field " + std::to_string(_i) + " was required, but missing."); + "Field " + std::to_string(_i) + " was required, but missing.", + ErrorKind::missing_field); return; } else if constexpr (std::is_nothrow_default_constructible_v< CurrentType>) { @@ -114,7 +115,8 @@ class TupleReader { "Field " + std::to_string(_i) + " was missing, and its default value could not be " "constructed: " + - e.what()); + e.what(), + ErrorKind::missing_field); return; } } diff --git a/include/rfl/parsing/VectorReader.hpp b/include/rfl/parsing/VectorReader.hpp index 2e22fef88..36813dfcc 100644 --- a/include/rfl/parsing/VectorReader.hpp +++ b/include/rfl/parsing/VectorReader.hpp @@ -79,7 +79,8 @@ class VectorReader { } else if constexpr (is_inplace_vector_v) { if (!vec_->try_emplace_back(std::move(*res))) { return Error("Too many elements, capacity is " + - std::to_string(vec_->capacity()) + "."); + std::to_string(vec_->capacity()) + ".", + ErrorKind::invalid_length); } } else { vec_->emplace_back(std::move(*res)); diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..690a5e898 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -186,8 +186,9 @@ class ViewReader { if (!already_assigned) { std::stringstream stream; stream << "Value named '" << _current_name_or_index << "' not used."; - _errors->emplace_back(make_nested_error( - to_path_segment(_current_name_or_index), stream.str())); + _errors->emplace_back( + make_nested_error(to_path_segment(_current_name_or_index), + stream.str(), ErrorKind::unknown_field)); } } } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..e264413c7 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -138,8 +138,8 @@ class ViewReaderWithDefault { stream << "Value named '" << std::string(_current_name) << "' not used. Remove the rfl::NoExtraFields processor or add " "rfl::ExtraFields to avoid this error message."; - _errors->emplace_back( - make_nested_error(std::string(_current_name), stream.str())); + _errors->emplace_back(make_nested_error( + std::string(_current_name), stream.str(), ErrorKind::unknown_field)); } } } diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 72512ff66..8c1f7a5ad 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -62,7 +62,7 @@ class ViewReaderWithDefaultAndStrippedFieldNames { std::stringstream stream; stream << "Expected a maximum of " << std::to_string(size_) << " fields, but got at least one more."; - return Error(stream.str()); + return Error(stream.str(), ErrorKind::invalid_length); } assign_to_field_i(_var, std::make_integer_sequence()); ++i_; diff --git a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp index 2b356f807..66531aa0c 100644 --- a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp @@ -59,7 +59,7 @@ class ViewReaderWithStrippedFieldNames { std::stringstream stream; stream << "Expected a maximum of " << std::to_string(size_) << " fields, but got at least one more."; - return Error(stream.str()); + return Error(stream.str(), ErrorKind::invalid_length); } assign_to_field_i(_var, std::make_integer_sequence()); ++i_; diff --git a/include/rfl/parsing/wrap_error.hpp b/include/rfl/parsing/wrap_error.hpp index 0a5fb625e..58f30639e 100644 --- a/include/rfl/parsing/wrap_error.hpp +++ b/include/rfl/parsing/wrap_error.hpp @@ -58,6 +58,9 @@ 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()); + } auto details = std::move(_err).details(); for (auto& detail : details) { if (detail.path.empty()) { @@ -73,12 +76,14 @@ RFL_COLD inline Error wrap_error(const std::string_view _prefix, Error&& _err) { * * @param _segment The location of the nested value relative to its parent. * @param _msg The error message. + * @param _kind Coarse classification of the error. * @return The error as seen from the parent. */ RFL_COLD inline Error make_nested_error( - const ErrorDetail::PathSegment& _segment, std::string _msg) { + const ErrorDetail::PathSegment& _segment, std::string _msg, + const ErrorKind _kind = ErrorKind::other) { auto details = std::vector( - {ErrorDetail{.path = {_segment}, .message = _msg}}); + {ErrorDetail{.path = {_segment}, .message = _msg, .kind = _kind}}); return Error(std::move(_msg), std::move(details)); } diff --git a/src/rfl/Generic.cpp b/src/rfl/Generic.cpp index 463a522b8..ce92c66c8 100644 --- a/src/rfl/Generic.cpp +++ b/src/rfl/Generic.cpp @@ -106,42 +106,49 @@ Result Generic::to_double() const noexcept { } return error( "rfl::Generic: Could not cast the underlying value to a double " - "without loss of precision."); + "without loss of precision.", + ErrorKind::invalid_value); } return error( - "rfl::Generic: Could not cast the underlying value to a double."); + "rfl::Generic: Could not cast the underlying value to a double.", + ErrorKind::invalid_type); } Result Generic::to_int() const noexcept { if (auto* ptr = std::get_if(&value_)) { if (*ptr < static_cast(std::numeric_limits::min()) || *ptr > static_cast(std::numeric_limits::max())) { - return error("rfl::Generic: int64_t value out of range for int."); + return error("rfl::Generic: int64_t value out of range for int.", + ErrorKind::invalid_value); } return static_cast(*ptr); } return error( - "rfl::Generic: Could not cast the underlying value to an integer."); + "rfl::Generic: Could not cast the underlying value to an integer.", + ErrorKind::invalid_type); } Result Generic::to_int64() const noexcept { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( - "rfl::Generic: Could not cast the underlying value to an int64."); + "rfl::Generic: Could not cast the underlying value to an int64.", + ErrorKind::invalid_type); } Result Generic::to_object() const noexcept { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( "rfl::Generic: Could not cast the underlying value to an " - "rfl::Generic::Object."); + "rfl::Generic::Object.", + ErrorKind::invalid_type); } Result Generic::to_null() const noexcept { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( "rfl::Generic: Could not cast the underlying value to " - "rfl::Generic::Null."); + "rfl::Generic::Null.", + ErrorKind::invalid_type); } /// Casts the underlying value to a string or returns an rfl::Error, if the @@ -150,7 +157,8 @@ Result Generic::to_string() const noexcept { if (auto* ptr = std::get_if(&value_)) return *ptr; return error( "rfl::Generic: Could not cast the underlying value to a " - "string."); + "string.", + ErrorKind::invalid_type); } } // namespace rfl diff --git a/tests/json/test_error_details.cpp b/tests/json/test_error_details.cpp index ac5c16809..26137b10d 100644 --- a/tests/json/test_error_details.cpp +++ b/tests/json/test_error_details.cpp @@ -36,9 +36,11 @@ TEST(json, test_error_details_of_top_level_fields) { const auto expected = std::vector( {{.path = {"input_file"}, .message = "Size validation failed: Value expected to be greater " - "than or equal to 5, but got 4."}, + "than or equal to 5, but got 4.", + .kind = rfl::ErrorKind::constraint_violation}, {.path = {"output_file"}, - .message = "Field named 'output_file' not found."}}); + .message = "Field named 'output_file' not found.", + .kind = rfl::ErrorKind::missing_field}}); EXPECT_EQ(result.error().details(), expected); } diff --git a/tests/json/test_error_kind.cpp b/tests/json/test_error_kind.cpp new file mode 100644 index 000000000..548858421 --- /dev/null +++ b/tests/json/test_error_kind.cpp @@ -0,0 +1,451 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_json_error_kind { + +using Path = std::vector; + +enum class Mode { fast, safe }; + +struct Item { + std::string name; + rfl::Validator> count; +}; + +struct Config { + std::string host; + int port; + Mode mode; + rfl::Literal<"http", "https"> scheme; + std::vector items; +}; + +struct Circle { + double radius; +}; + +struct Square { + double width; +}; + +using Shape = rfl::TaggedUnion<"shape", Circle, Square>; + +struct EnvGuard { + std::vector keys; + + void set(const std::string& _key, const std::string& _val) { + keys.push_back(_key); +#ifdef _WIN32 + _putenv_s(_key.c_str(), _val.c_str()); +#else + setenv(_key.c_str(), _val.c_str(), 1); +#endif + } + + void unset(const std::string& _key) { +#ifdef _WIN32 + _putenv_s(_key.c_str(), ""); +#else + unsetenv(_key.c_str()); +#endif + } + + ~EnvGuard() { + for (const auto& k : keys) { + unset(k); + } + } +}; + +TEST(json, test_error_kind_inline_zero_alloc_and_helpers) { + static_assert(std::is_same_v, uint8_t>); + + const rfl::Error plain("plain message"); + EXPECT_EQ(plain.kind(), rfl::ErrorKind::other); + EXPECT_FALSE(rfl::internal::has_allocated_details(plain)); + ASSERT_EQ(plain.details().size(), 1u); + EXPECT_EQ(plain.details()[0].kind, rfl::ErrorKind::other); + + // Leaf classified errors store kind_ inline without allocating OptionalDetails. + const rfl::Error leaf_copy(std::string("bad"), rfl::ErrorKind::invalid_value); + EXPECT_EQ(leaf_copy.kind(), rfl::ErrorKind::invalid_value); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf_copy)); + EXPECT_EQ(leaf_copy.details().size(), 1u); + EXPECT_EQ(leaf_copy.details()[0].kind, rfl::ErrorKind::invalid_value); + EXPECT_EQ(leaf_copy.details()[0].message, "bad"); + EXPECT_TRUE(leaf_copy.details()[0].path.empty()); + + rfl::Error leaf_move(std::string("moved"), rfl::ErrorKind::syntax_error); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf_move)); + const auto moved_details = std::move(leaf_move).details(); + ASSERT_EQ(moved_details.size(), 1u); + EXPECT_EQ(moved_details[0].kind, rfl::ErrorKind::syntax_error); + EXPECT_EQ(moved_details[0].message, "moved"); + + // rfl::error(what, kind) and empty-path overload stay zero-alloc. + const auto leaf_helper = rfl::error("bad value", rfl::ErrorKind::invalid_value); + EXPECT_EQ(leaf_helper.error().kind(), rfl::ErrorKind::invalid_value); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf_helper.error())); + + const auto empty_path = + rfl::error("bad value", rfl::ErrorKind::invalid_value, {}); + EXPECT_EQ(empty_path.error().kind(), rfl::ErrorKind::invalid_value); + EXPECT_FALSE(rfl::internal::has_allocated_details(empty_path.error())); + + // Non-empty path allocates details and preserves path & kind. + const auto nested_helper = + rfl::error("bad value", rfl::ErrorKind::invalid_value, {"port"}); + EXPECT_TRUE(rfl::internal::has_allocated_details(nested_helper.error())); + EXPECT_EQ(nested_helper.error().kind(), rfl::ErrorKind::invalid_value); + ASSERT_EQ(nested_helper.error().details().size(), 1u); + EXPECT_EQ(nested_helper.error().details()[0].path, (Path{"port"})); + EXPECT_EQ(nested_helper.error().details()[0].kind, + rfl::ErrorKind::invalid_value); + EXPECT_EQ(nested_helper.error().what(), "bad value"); + + // Aggregate initialization without .kind remains backward-compatible. + const rfl::ErrorDetail compat{.path = {"x"}, .message = "msg"}; + EXPECT_EQ(compat.kind, rfl::ErrorKind::other); + + // Leaf errors produced by JSON & Validator reads do not allocate details. + const auto leaf_json = rfl::json::read("\"abc\""); + ASSERT_FALSE(leaf_json); + EXPECT_EQ(leaf_json.error().kind(), rfl::ErrorKind::invalid_type); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf_json.error())); + + const auto leaf_val = + rfl::json::read>>("0"); + ASSERT_FALSE(leaf_val); + EXPECT_EQ(leaf_val.error().kind(), rfl::ErrorKind::constraint_violation); + EXPECT_FALSE(rfl::internal::has_allocated_details(leaf_val.error())); +} + +TEST(json, test_error_kind_syntax_error) { + const auto res = rfl::json::read("{not valid json"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().kind(), rfl::ErrorKind::syntax_error); + EXPECT_FALSE(rfl::internal::has_allocated_details(res.error())); + ASSERT_EQ(res.error().details().size(), 1u); + EXPECT_TRUE(res.error().details()[0].path.empty()); + EXPECT_EQ(res.error().details()[0].kind, rfl::ErrorKind::syntax_error); +} + +TEST(json, test_error_kind_multi_error_aggregation) { + const std::string json_str = R"({ + "port": "not_an_int", + "mode": "turbo", + "scheme": "ftp", + "extra": 123, + "items": [ + {"name": "ok", "count": 0} + ] + })"; + + const auto res = rfl::json::read(json_str); + ASSERT_FALSE(res); + + const auto details = res.error().details(); + ASSERT_EQ(details.size(), 6u) << res.error().what(); + + EXPECT_EQ(details[0].path, (Path{"port"})); + EXPECT_EQ(details[0].kind, rfl::ErrorKind::invalid_type); + + EXPECT_EQ(details[1].path, (Path{"mode"})); + EXPECT_EQ(details[1].kind, rfl::ErrorKind::invalid_value); + + EXPECT_EQ(details[2].path, (Path{"scheme"})); + EXPECT_EQ(details[2].kind, rfl::ErrorKind::invalid_value); + + EXPECT_EQ(details[3].path, (Path{"extra"})); + EXPECT_EQ(details[3].kind, rfl::ErrorKind::unknown_field); + + EXPECT_EQ(details[4].path, (Path{"items", size_t{0}, "count"})); + EXPECT_EQ(details[4].kind, rfl::ErrorKind::constraint_violation); + + EXPECT_EQ(details[5].path, (Path{"host"})); + EXPECT_EQ(details[5].kind, rfl::ErrorKind::missing_field); + + // Error::kind() returns the first detail's kind for multi-error results. + EXPECT_EQ(res.error().kind(), details[0].kind); +} + +TEST(json, test_error_kind_invalid_type_vs_invalid_value) { + // Structural type mismatch -> invalid_type + const auto bad_obj = rfl::json::read("[1, 2]"); + ASSERT_FALSE(bad_obj); + EXPECT_EQ(bad_obj.error().kind(), rfl::ErrorKind::invalid_type); + + const auto bad_arr = rfl::json::read>(R"({"a": 1})"); + ASSERT_FALSE(bad_arr); + EXPECT_EQ(bad_arr.error().kind(), rfl::ErrorKind::invalid_type); + + // Wrong wire type for unsigned integer -> invalid_type + const auto str_for_uint = rfl::json::read("\"abc\""); + ASSERT_FALSE(str_for_uint); + EXPECT_EQ(str_for_uint.error().kind(), rfl::ErrorKind::invalid_type); + + // Negative integer for unsigned target (right wire type, bad domain) -> + // invalid_value + const auto neg_for_uint = rfl::json::read("-1"); + ASSERT_FALSE(neg_for_uint); + EXPECT_EQ(neg_for_uint.error().kind(), rfl::ErrorKind::invalid_value); + EXPECT_EQ(neg_for_uint.error().what(), "Could not cast to uint."); + + // Positive integer out of range for target type -> invalid_value + const auto overflow = rfl::json::read("300"); + ASSERT_FALSE(overflow); + EXPECT_EQ(overflow.error().kind(), rfl::ErrorKind::invalid_value); + + // Base64, bitset, and time_point domain errors -> invalid_value + const auto bad_b64 = rfl::json::read("\"!!!\""); + ASSERT_FALSE(bad_b64); + EXPECT_EQ(bad_b64.error().kind(), rfl::ErrorKind::invalid_value); + + const auto bad_bits = rfl::json::read>("\"1020\""); + ASSERT_FALSE(bad_bits); + EXPECT_EQ(bad_bits.error().kind(), rfl::ErrorKind::invalid_value); + + const auto bad_tp = + rfl::json::read("\"not-a-date\""); + ASSERT_FALSE(bad_tp); + EXPECT_EQ(bad_tp.error().kind(), rfl::ErrorKind::invalid_value); +} + +TEST(json, test_error_kind_tagged_union_preserves_inner_and_disc_errors) { + // Unknown discriminator value -> invalid_value at [tag] + const auto tu_unknown = + rfl::json::read(R"({"shape": "Triangle", "sides": 3})"); + ASSERT_FALSE(tu_unknown); + EXPECT_EQ(tu_unknown.error().kind(), rfl::ErrorKind::invalid_value); + ASSERT_EQ(tu_unknown.error().details().size(), 1u); + EXPECT_EQ(tu_unknown.error().details()[0].path, (Path{"shape"})); + + // Missing discriminator field -> missing_field at [tag] (not overwritten!) + const auto tu_missing_disc = rfl::json::read(R"({"radius": 1.0})"); + ASSERT_FALSE(tu_missing_disc); + EXPECT_EQ(tu_missing_disc.error().kind(), rfl::ErrorKind::missing_field); + ASSERT_EQ(tu_missing_disc.error().details().size(), 1u); + EXPECT_EQ(tu_missing_disc.error().details()[0].path, (Path{"shape"})); + + // Non-string discriminator field -> invalid_type at [tag] (not overwritten!) + const auto tu_bad_disc_type = + rfl::json::read(R"({"shape": 42, "radius": 1.0})"); + ASSERT_FALSE(tu_bad_disc_type); + EXPECT_EQ(tu_bad_disc_type.error().kind(), rfl::ErrorKind::invalid_type); + ASSERT_EQ(tu_bad_disc_type.error().details().size(), 1u); + EXPECT_EQ(tu_bad_disc_type.error().details()[0].path, (Path{"shape"})); + + // Matched alternative missing a field -> missing_field preserved + const auto tu_missing = rfl::json::read(R"({"shape": "Circle"})"); + ASSERT_FALSE(tu_missing); + EXPECT_EQ(tu_missing.error().kind(), rfl::ErrorKind::missing_field); + ASSERT_EQ(tu_missing.error().details().size(), 1u); + EXPECT_EQ(tu_missing.error().details()[0].path, (Path{"radius"})); + + // Matched alternative wrong field type -> invalid_type preserved + const auto tu_bad_field = + rfl::json::read(R"({"shape": "Circle", "radius": "big"})"); + ASSERT_FALSE(tu_bad_field); + EXPECT_EQ(tu_bad_field.error().kind(), rfl::ErrorKind::invalid_type); + ASSERT_EQ(tu_bad_field.error().details().size(), 1u); + EXPECT_EQ(tu_bad_field.error().details()[0].path, (Path{"radius"})); +} + +TEST(json, test_error_kind_variant_field_variant_array_tuple_and_map) { + const auto var_res = rfl::json::read>("\"abc\""); + ASSERT_FALSE(var_res); + EXPECT_EQ(var_res.error().kind(), rfl::ErrorKind::invalid_value); + + const auto rfl_var_res = rfl::json::read>("\"abc\""); + ASSERT_FALSE(rfl_var_res); + EXPECT_EQ(rfl_var_res.error().kind(), rfl::ErrorKind::invalid_value); + + // Externally tagged FieldVariant + using FV = rfl::Variant, + rfl::Field<"square", Square>>; + const auto fv_empty = rfl::json::read("{}"); + ASSERT_FALSE(fv_empty); + EXPECT_EQ(fv_empty.error().kind(), rfl::ErrorKind::invalid_value); + + const auto fv_unknown = rfl::json::read(R"({"tri": {}})"); + ASSERT_FALSE(fv_unknown); + EXPECT_EQ(fv_unknown.error().kind(), rfl::ErrorKind::invalid_value); + + const auto fv_inner_missing = rfl::json::read(R"({"circle": {}})"); + ASSERT_FALSE(fv_inner_missing); + EXPECT_EQ(fv_inner_missing.error().kind(), rfl::ErrorKind::missing_field); + ASSERT_EQ(fv_inner_missing.error().details().size(), 1u); + EXPECT_EQ(fv_inner_missing.error().details()[0].path, + (Path{"circle", "radius"})); + + // NoFieldNames overflow -> invalid_length + const auto nfn_overflow = + rfl::json::read(R"(["ok", 1, "extra"])"); + ASSERT_FALSE(nfn_overflow); + EXPECT_EQ(nfn_overflow.error().kind(), rfl::ErrorKind::invalid_length); + + // Bad rfl::Timestamp -> invalid_value + const auto bad_ts = + rfl::json::read>(R"("not-a-date")"); + ASSERT_FALSE(bad_ts); + EXPECT_EQ(bad_ts.error().kind(), rfl::ErrorKind::invalid_value); + + // Custom type whose from_reflection returns a type U convertible to T + struct ConvertibleProxy { + int v; + }; + struct CustomConvertible { + using ReflectionType = int; + int value = 0; + CustomConvertible(ConvertibleProxy _p) : value(_p.v) {} + static ConvertibleProxy from_reflection(int _x) { return {_x + 1}; } + int reflection() const { return value; } + }; + const auto conv = rfl::json::read("41"); + ASSERT_TRUE(conv); + EXPECT_EQ(conv->value, 42); + + // Tuple & Array alignment: missing tuple slot -> missing_field; + // tuple overflow & std::array size mismatch -> invalid_length. + const auto tup_missing = rfl::json::read>("[1]"); + ASSERT_FALSE(tup_missing); + EXPECT_EQ(tup_missing.error().kind(), rfl::ErrorKind::missing_field); + + const auto tup_extra = + rfl::json::read>(R"([1, "a", 2])"); + ASSERT_FALSE(tup_extra); + EXPECT_EQ(tup_extra.error().kind(), rfl::ErrorKind::invalid_length); + + const auto arr_missing = rfl::json::read>("[1]"); + ASSERT_FALSE(arr_missing); + EXPECT_EQ(arr_missing.error().kind(), rfl::ErrorKind::invalid_length); + + const auto arr_extra = rfl::json::read>("[1, 2, 3]"); + ASSERT_FALSE(arr_extra); + EXPECT_EQ(arr_extra.error().kind(), rfl::ErrorKind::invalid_length); + + // Map with numeric / validated key + const auto bad_num_key = + rfl::json::read>(R"({"not_an_int": "v"})"); + ASSERT_FALSE(bad_num_key); + EXPECT_EQ(bad_num_key.error().kind(), rfl::ErrorKind::invalid_value); + + using ValidKey = rfl::Validator>>; + const auto bad_val_key = + rfl::json::read>(R"({"ab": 1})"); + ASSERT_FALSE(bad_val_key); + EXPECT_EQ(bad_val_key.error().kind(), rfl::ErrorKind::constraint_violation); + + // FailFast preserves kind + const auto ff_res = + rfl::json::read(R"({"name": "a", "count": 0})"); + ASSERT_FALSE(ff_res); + EXPECT_EQ(ff_res.error().kind(), rfl::ErrorKind::constraint_violation); +} + +TEST(json, test_error_kind_generic_reader) { + // Type mismatch -> invalid_type + rfl::Generic::Object obj; + obj["name"] = std::string("ok"); + obj["count"] = std::string("not_an_int"); + const auto bad_type = rfl::from_generic(rfl::Generic(obj)); + ASSERT_FALSE(bad_type); + EXPECT_EQ(bad_type.error().kind(), rfl::ErrorKind::invalid_type); + + // Missing field -> missing_field + rfl::Generic::Object incomplete; + incomplete["name"] = std::string("ok"); + const auto missing = rfl::from_generic(rfl::Generic(incomplete)); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().kind(), rfl::ErrorKind::missing_field); + + // Out-of-range int64 -> int in Generic -> invalid_value + const rfl::Generic huge_int(static_cast(1LL << 40)); + const auto overflow = rfl::from_generic(huge_int); + ASSERT_FALSE(overflow); + EXPECT_EQ(overflow.error().kind(), rfl::ErrorKind::invalid_value); + + // Direct Generic::Object::get missing key -> missing_field + const auto missing_key = incomplete.get("count"); + ASSERT_FALSE(missing_key); + EXPECT_EQ(missing_key.error().kind(), rfl::ErrorKind::missing_field); +} + +TEST(json, test_error_kind_env_reader) { + struct EnvConfig { + std::string rfl_ek_host; + int rfl_ek_port; + bool rfl_ek_debug; + double rfl_ek_rate; + }; + + EnvGuard guard; + guard.unset("RFL_EK_HOST"); + guard.unset("RFL_EK_PORT"); + guard.unset("RFL_EK_DEBUG"); + guard.unset("RFL_EK_RATE"); + + // Bad lexical int/bool/float parse -> invalid_value (NOT invalid_type!) + guard.set("RFL_EK_HOST", "localhost"); + guard.set("RFL_EK_PORT", "not_a_port"); + guard.set("RFL_EK_DEBUG", "maybe"); + guard.set("RFL_EK_RATE", "nan_ish"); + + const auto res = rfl::env::read(); + ASSERT_FALSE(res); + const auto details = res.error().details(); + ASSERT_EQ(details.size(), 3u) << res.error().what(); + EXPECT_EQ(details[0].kind, rfl::ErrorKind::invalid_value); + EXPECT_EQ(details[1].kind, rfl::ErrorKind::invalid_value); + EXPECT_EQ(details[2].kind, rfl::ErrorKind::invalid_value); + + // Missing env variable -> missing_field (both struct-level and direct reader) + guard.unset("RFL_EK_HOST"); + guard.set("RFL_EK_PORT", "8080"); + guard.set("RFL_EK_DEBUG", "true"); + guard.set("RFL_EK_RATE", "1.5"); + + const auto missing = rfl::env::read(); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().kind(), rfl::ErrorKind::missing_field); + + const auto missing_direct = rfl::env::Reader{}.to_basic_type( + rfl::env::InputEnvVarType{.path = "RFL_EK_HOST"}); + ASSERT_FALSE(missing_direct); + EXPECT_EQ(missing_direct.error().kind(), rfl::ErrorKind::missing_field); +} + +TEST(json, test_error_kind_io_error_and_wire_names) { + const auto missing_file = + rfl::json::load("/nonexistent/rfl_error_kind_missing_file.json"); + ASSERT_FALSE(missing_file); + EXPECT_EQ(missing_file.error().kind(), rfl::ErrorKind::io_error); + EXPECT_FALSE(rfl::internal::has_allocated_details(missing_file.error())); + + const auto unwritable = rfl::json::save( + "/nonexistent/rfl_error_kind_dir/out.json", Item{.name = "a", .count = 1}); + ASSERT_FALSE(unwritable); + EXPECT_EQ(unwritable.error().kind(), rfl::ErrorKind::io_error); + + // Verify JSON wire serialization of ErrorDetail::kind names. + const auto err = rfl::error("bad", rfl::ErrorKind::invalid_length, {"items"}); + const auto serialized = rfl::json::write(err.error().details()); + EXPECT_NE(serialized.find(R"("kind":"invalid_length")"), std::string::npos) + << serialized; +} + +} // namespace test_json_error_kind