From c36baf8d0bf60dacbcc9301b6d20758092262e3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dr=2E=20Patrick=20Urbanke=20=28=E5=8A=89=E8=87=AA=E6=88=90?= =?UTF-8?q?=29?= Date: Thu, 24 Apr 2025 08:43:32 +0800 Subject: [PATCH] Better error handling for YYJSON write (#413) --- include/rfl/json/write.hpp | 17 +++++++++++++++-- tests/json/test_named_tuple.cpp | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 tests/json/test_named_tuple.cpp diff --git a/include/rfl/json/write.hpp b/include/rfl/json/write.hpp index 4cc85ab4..7457714d 100644 --- a/include/rfl/json/write.hpp +++ b/include/rfl/json/write.hpp @@ -1,6 +1,7 @@ #ifndef RFL_JSON_WRITE_HPP_ #define RFL_JSON_WRITE_HPP_ +#include #if __has_include() #include #else @@ -28,7 +29,13 @@ std::string write(const auto& _obj, const yyjson_write_flag _flag = 0) { using ParentType = parsing::Parent; auto w = Writer(yyjson_mut_doc_new(NULL)); Parser>::write(w, _obj, typename ParentType::Root{}); - const char* json_c_str = yyjson_mut_write(w.doc_, _flag, NULL); + yyjson_write_err err; + const char* json_c_str = + yyjson_mut_write_opts(w.doc_, _flag, NULL, NULL, &err); + if (!json_c_str) { + throw std::runtime_error("An error occured while writing to JSON: " + + std::string(err.msg)); + } const auto json_str = std::string(json_c_str); free((void*)json_c_str); yyjson_mut_doc_free(w.doc_); @@ -43,7 +50,13 @@ std::ostream& write(const auto& _obj, std::ostream& _stream, using ParentType = parsing::Parent; auto w = Writer(yyjson_mut_doc_new(NULL)); Parser>::write(w, _obj, typename ParentType::Root{}); - const char* json_c_str = yyjson_mut_write(w.doc_, _flag, NULL); + yyjson_write_err err; + const char* json_c_str = + yyjson_mut_write_opts(w.doc_, _flag, NULL, NULL, &err); + if (!json_c_str) { + throw std::runtime_error("An error occured while writing to JSON: " + + std::string(err.msg)); + } _stream << json_c_str; free((void*)json_c_str); yyjson_mut_doc_free(w.doc_); diff --git a/tests/json/test_named_tuple.cpp b/tests/json/test_named_tuple.cpp new file mode 100644 index 00000000..1ab33497 --- /dev/null +++ b/tests/json/test_named_tuple.cpp @@ -0,0 +1,19 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_named_tuple { + +TEST(json, test_named_tuple) { + const auto homer = rfl::make_field<"firstName", std::string>("Homer") * + rfl::make_field<"lastName", std::string>("Simpson") * + rfl::make_field<"age">(45); + + write_and_read(homer, + R"({"firstName":"Homer","lastName":"Simpson","age":45})"); +} +} // namespace test_named_tuple