From 4a2310a3a09a4e9bde51b003c2a562a4a49cfabf Mon Sep 17 00:00:00 2001 From: Philipp Otterbein Date: Tue, 31 Dec 2024 17:52:06 +0100 Subject: [PATCH] toJSON: re-throw serialization exception --- src/libexpr/value-to-json.cc | 6 +++++- src/libexpr/value-to-json.hh | 3 +++ tests/functional/lang/eval-fail-toJSON-non-utf-8.err.exp | 8 ++++++++ tests/functional/lang/eval-fail-toJSON-non-utf-8.nix | 1 + 4 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tests/functional/lang/eval-fail-toJSON-non-utf-8.err.exp create mode 100644 tests/functional/lang/eval-fail-toJSON-non-utf-8.nix diff --git a/src/libexpr/value-to-json.cc b/src/libexpr/value-to-json.cc index 8044fe347..5aa4fe4fd 100644 --- a/src/libexpr/value-to-json.cc +++ b/src/libexpr/value-to-json.cc @@ -108,7 +108,11 @@ json printValueAsJSON(EvalState & state, bool strict, void printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, std::ostream & str, NixStringContext & context, bool copyToStore) { - str << printValueAsJSON(state, strict, v, pos, context, copyToStore); + try { + str << printValueAsJSON(state, strict, v, pos, context, copyToStore); + } catch (nlohmann::json::exception & e) { + throw JSONSerializationError("JSON serialization error: %s", e.what()); + } } json ExternalValueBase::printValueAsJSON(EvalState & state, bool strict, diff --git a/src/libexpr/value-to-json.hh b/src/libexpr/value-to-json.hh index 47ac90313..867c4e3a8 100644 --- a/src/libexpr/value-to-json.hh +++ b/src/libexpr/value-to-json.hh @@ -16,4 +16,7 @@ nlohmann::json printValueAsJSON(EvalState & state, bool strict, void printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, std::ostream & str, NixStringContext & context, bool copyToStore = true); + +MakeError(JSONSerializationError, Error); + } diff --git a/tests/functional/lang/eval-fail-toJSON-non-utf-8.err.exp b/tests/functional/lang/eval-fail-toJSON-non-utf-8.err.exp new file mode 100644 index 000000000..129d58bcb --- /dev/null +++ b/tests/functional/lang/eval-fail-toJSON-non-utf-8.err.exp @@ -0,0 +1,8 @@ +error: + … while calling the 'toJSON' builtin + at /pwd/lang/eval-fail-toJSON-non-utf-8.nix:1:1: + 1| builtins.toJSON "_invalid UTF-8: ÿ_" + | ^ + 2| + + error: JSON serialization error: [json.exception.type_error.316] invalid UTF-8 byte at index 16: 0xFF diff --git a/tests/functional/lang/eval-fail-toJSON-non-utf-8.nix b/tests/functional/lang/eval-fail-toJSON-non-utf-8.nix new file mode 100644 index 000000000..bd1f74de7 --- /dev/null +++ b/tests/functional/lang/eval-fail-toJSON-non-utf-8.nix @@ -0,0 +1 @@ +builtins.toJSON "_invalid UTF-8: ÿ_"