From ea3ce3632cec598c14d9389b06739c89521940e4 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 21 Oct 2023 14:19:32 +0200 Subject: [PATCH] Added support for better error messages --- include/rfl/Result.hpp | 6 +-- include/rfl/parsing/Parser.hpp | 83 ++++++++++++++++++++++++++++++---- tests/test_error_messages.hpp | 42 +++++++++++++++++ tests/tests.cpp | 2 + 4 files changed, 121 insertions(+), 12 deletions(-) create mode 100644 tests/test_error_messages.hpp diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 5423fd1e..2c84ffc4 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -211,10 +211,10 @@ class Result { Result or_else(const F& _f) { const auto handle_variant = [&](TOrError&& _t_or_err) -> Result { - if constexpr (std::is_same()) { - return _f(std::forward(_t_or_err)); + if constexpr (std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); } else { - return std::forward(_t_or_err); + return std::forward(_t_or_err); } }; return std::visit(handle_variant, diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index c8d35ca0..aeb4fb3a 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -392,7 +392,10 @@ struct Parser> { if (!f) { if constexpr (is_required()) { const auto key = FieldType::name_.str(); - return Error("Field named '" + key + "' not found!"); + return collect_errors( + _r, _fields_vec, + std::vector( + {Error("Field named '" + key + "' not found!")})); } else { return build_named_tuple_recursively( _r, _fields_vec, std::move(_args)..., @@ -406,7 +409,64 @@ struct Parser> { FieldType(std::move(_value))); }; - return get_value(_r, *f).and_then(build); + const auto handle_error = [&](Error&& _error) { + return collect_errors( + _r, _fields_vec, std::vector({std::move(_error)})); + }; + + return get_value(_r, *f) + .or_else(handle_error) + .and_then(build); + } + } + + /// If something went wrong, we want to collect all of the errors - it's + /// just good UX. + template + static Error collect_errors( + const ReaderType& _r, + const std::array, sizeof...(FieldTypes)>& + _fields_vec, + std::vector _errors) noexcept { + if constexpr (_i == sizeof...(FieldTypes)) { + if (_errors.size() == 1) { + return std::move(_errors[0]); + } else { + std::string msg = + "Found " + std::to_string(_errors.size()) + " errors:"; + for (size_t i = 0; i < _errors.size(); ++i) { + msg += "\n" + std::to_string(i + 1) + ") " + + _errors.at(i).what(); + } + return Error(msg); + } + } else { + using FieldType = typename std::tuple_element< + _i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get<_i>(_fields_vec); + + if (!f) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + _errors.emplace_back( + Error("Field named '" + key + "' not found.")); + } + return collect_errors<_i + 1>(_r, _fields_vec, + std::move(_errors)); + } + + const auto add_error_if_applicable = + [&](Error&& _error) -> Result { + _errors.emplace_back(std::move(_error)); + return _error; + }; + + get_value(_r, *f).or_else(add_error_if_applicable); + + return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors)); } } @@ -447,8 +507,8 @@ struct Parser> { NamedTuple>::field_indices_; } - /// Retrieves the value from the object. This is mainly needed to generate a - /// better error message. + /// Retrieves the value from the object. This is mainly needed to + /// generate a better error message. template static auto get_value(const ReaderType& _r, InputVarType _var) noexcept { const auto embellish_error = [&](const Error& _e) { @@ -654,7 +714,8 @@ struct Parser>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; @@ -867,7 +929,8 @@ struct FieldVariantParser { const std::variant& _v) noexcept { static_assert( internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); const auto handle = [&](const auto& _field) { const auto named_tuple = @@ -887,7 +950,8 @@ struct FieldVariantParser { InputVarType* _var) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { return Error( - "Could not parse std::variant, could not match field named '" + + "Could not parse std::variant, could not match field named " + "'" + _disc_value + "'."); } else { using FieldType = std::decay_t> { /// This can be used for data structures that would be expressed as array in /// serialized format (std::vector, std::set, std::deque, ...), -/// but also includes map-like types, when the key is not of type std::string. +/// but also includes map-like types, when the key is not of type +/// std::string. template struct VectorParser { public: diff --git a/tests/test_error_messages.hpp b/tests/test_error_messages.hpp new file mode 100644 index 00000000..139c9dc0 --- /dev/null +++ b/tests/test_error_messages.hpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_error_messages() { + std::cout << "test_error_messages" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Field<"children", std::vector> children; + }; + + const std::string faulty_string = + R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})"; + + const auto result = rfl::json::read(faulty_string); + + const std::string expected = R"(Found 3 errors: +1) Failed to parse field 'lastName': Could not cast to string. +2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'. +3) Field named 'children' not found.)"; + + if (!result.error()) { + std::cout << "Expected an error, got none." << std::endl << std::endl; + } + + if (result.error().value().what() != expected) { + std::cout << "Expected: " << std::endl + << expected << std::endl + << "Got:" << std::endl + << result.error().value().what() << std::endl + << std::endl; + } + + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 6f6afdd6..871285c4 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -8,6 +8,7 @@ #include "test_custom_class4.hpp" #include "test_default_values.hpp" #include "test_deque.hpp" +#include "test_error_messages.hpp" #include "test_field_variant.hpp" #include "test_flatten.hpp" #include "test_forward_list.hpp" @@ -63,6 +64,7 @@ int main() { test_unordered_multiset(); test_string_map(); test_string_unordered_map(); + test_error_messages(); test_custom_class1(); test_custom_class2();