Skip to content

Add machine-readable Error::code() and ErrorDetail::code for validator errors - #205

Draft
clockblocker wants to merge 1 commit into
discuss/error-kindfrom
discuss/error-code
Draft

clockblocker wants to merge 1 commit into
discuss/error-kindfrom
discuss/error-code

Conversation

@clockblocker

@clockblocker clockblocker commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

AI-authored below this line.

Stacked on: #196 (discuss/error-kind)

Problem

Even with ErrorKind::constraint_violation, every rfl::Validator failure lands in the same coarse bucket, forcing callers to regex-match English Error::what() messages to tell a minimum bound from a pattern or custom rule. API error payloads, localized UI diagnostics, and structured config validators need a stable, machine-readable rule identifier alongside path and kind.

Proposed API

Adds Error::code() (std::string_view, empty when unset) and ErrorDetail::code (std::string) populated automatically by all built-in validators and optionally by custom validators:

#include <rfl.hpp>
#include <rfl/json.hpp>

struct MustBeEven {
  static constexpr std::string_view code = "even";
  static rfl::Result<int> validate(const int _v) {
    if (_v % 2 != 0) return rfl::error("Expected an even integer.");
    return _v;
  }
  template <class T>
  static rfl::parsing::schema::ValidationType to_schema() {
    return rfl::parsing::schema::ValidationType{
        rfl::parsing::schema::ValidationType::AllOf{}};
  }
};

struct Request {
  rfl::Validator<std::string, rfl::Size<rfl::Minimum<1>>> name;
  rfl::Validator<int, MustBeEven, rfl::Minimum<0>> batch_size;
};

const auto res = rfl::json::read<Request>(R"({"name": "", "batch_size": 3})");
// details()[0]: path = {"name"},       kind = constraint_violation, code = "size.minimum"
// details()[1]: path = {"batch_size"}, kind = constraint_violation, code = "even"

// Per-error override (takes precedence over a declarative static `code`):
const auto err = rfl::error("Must not be negative.",
                            rfl::ErrorKind::constraint_violation,
                            "non_negative");
  • Zero allocation & zero sizeof(rfl::Error) growth: Packs a 1-byte tag into ErrorKind's tail padding covering all 27 canonical built-in validator codes.
  • Custom validator support: Works either per-error via rfl::error(...) or declaratively via a static code string member, with per-error codes taking precedence.
  • Full propagation: Preserves codes through composite validators (AllOf, Size, CodePoints), validated map keys, and nested error wrapping while keeping prefix-only wrapping allocation-free for built-in codes.

Open Design Questions

  1. Implicit static V::code opt-in vs explicit trait: Any custom validator defining a string-convertible static member named code automatically populates ErrorDetail::code. Should that remain convention-based, or require an explicit specialization/tag (or rfl::error(...) calls only) so an unrelated static code constant cannot leak into API responses?
  2. Canonical code naming & PatternValidator aliases: Are the 27 canonical names ("minimum", "size.minimum", "code_points.maximum", "pattern", etc.) the right wire vocabulary, and should aliases like rfl::Email continue emitting "pattern" or expose a distinct rule code?
  3. Compiled library symbol vs header-only inline: Placing the small lookup switch tables out-of-line in the compiled library keeps headers light, but means calling Error::code() or constructing coded errors requires linking reflectcpp::reflectcpp rather than using reflectcpp::headers alone. Should those lookup tables stay out-of-line or be inline in the header?

Upstream Context

Direct stacked follow-up to #196 (discuss/error-kind) and merged upstream PR munich-data-engineering/reflect-cpp#766 (Error::details()), completing the structured diagnostic triple (path, kind, code) for validation failures.

@clockblocker

clockblocker commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner Author

AI-authored below this line.

For Agents — Provenance, Architecture & Review Metadata

  • Branch: discuss/error-code (base: #196 discuss/error-kind @ 9fe09b9cd0876f7f0fd780353f7e48374ddeac92)
  • Isolated Commit: 058f52259bbbcf685bdb10e647e5714096321f04 (discuss/ssot counterpart: f42f94f5)
  • Legacy Fork PR: #120 | Upstream Refs: Stacked on #196; follow-up to merged munich-data-engineering/reflect-cpp#766
  • Diff Footprint: +528/-33 (15 files) prod, +10/-2 (1 file) docs, +513/-1 (2 files) tests
  • Maintainer-Judge Score: 45/100 (18 files; 28-value BuiltinErrorCode wire vocabulary, implicit static V::code reflection opt-in, ErrorDetail::operator== change, and new out-of-line RFL_API TU src/rfl/internal/Error.cpp require upstream design sign-off.)
  • Decoupled Cross-PR Interop: None — identical to discuss/ssot.

Implementation Invariants & Rebase Notes

  • Hard parent dependency: Must stay rebased on top of #196 (discuss/error-kind); depends directly on ErrorKind, Error::kind_, has_allocated_details(), and set_error_kind_if_other().
  • Layout invariant: BuiltinErrorCode builtin_code_ MUST immediately follow ErrorKind kind_ in rfl::internal::Error so both uint8_t fields share the same alignment word (asserted via static_assert(sizeof(rfl::Error) == sizeof(PreCodeErrorLayout)) in test_error_code.cpp).
  • Braced-init overload guard: Keep rfl::error(what, kind, Code&&) rejecting nullptr and non-string-view types so {"field"} and {} continue resolving to the PathSegment vector overload.
  • Header-only vs compiled library note: Error.hpp declares 4 RFL_API symbols defined in src/rfl/internal/Error.cpp (src/reflectcpp.cpp). If upstream wants reflectcpp::headers consumers to call Error::code() without linking reflectcpp::reflectcpp, move those 4 small switch helpers to inline in Error.hpp.
  • GCC -Werror=nonnull guard: validator_code.hpp guards constant nullptr V::code via if constexpr (requires { std::bool_constant<V::code == nullptr>{}; }) to avoid GCC 13 -Werror=nonnull inside std::string_view(const char*).

Verification Receipt

  • Verified: Clang 23.1.6 (-DREFLECTCPP_STRICT_WARNINGS=ON, isolated branch): 0 library warnings; 13/13 tests passed (tests/json: test_error_code.cpp, test_error_details.cpp); 9 standalone headers clean (AllOf, AnyOf, CodePoints, OneOf, PatternValidator, Result, Size, Validator, comparisons).

Stacked on discuss/error-kind. Adds machine-readable Error::code() (std::string_view) and ErrorDetail::code (std::string, compared in operator==) for built-in and custom validators.

Key changes:
- Pack a 1-byte BuiltinErrorCode enum into ErrorKind's tail padding on rfl::Error so built-in validator codes (equal_to, not_equal_to, minimum, exclusive_minimum, maximum, exclusive_maximum, pattern, any_of, one_of, size / size.*, code_points / code_points.*) incur zero heap allocation and zero sizeof(rfl::Error) growth.
- Move BuiltinErrorCode string/composition helpers out-of-line into src/rfl/internal/Error.cpp (wired into src/reflectcpp.cpp with RFL_API declarations).
- Support custom validator codes per-error via rfl::error(msg, kind[, path], code) or declaratively via a static code member in include/rfl/internal/validator_code.hpp.
- Propagate Error::code() through wrap_error and Size/CodePoints/AllOf/Validator wrappers.
- Add unit tests in tests/json/test_error_code.cpp and update docs/content/result.md.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant