Skip to content

Commit 693a793

Browse files
byrootetiennebarrie
authored andcommitted
JSON::GeneratorError expose invalid object
Fix: ruby/json#710 Makes it easier to debug why a given tree of objects can't be dumped as JSON. Co-Authored-By: Étienne Barrié <[email protected]>
1 parent 6805e88 commit 693a793

File tree

3 files changed

+70
-19
lines changed

3 files changed

+70
-19
lines changed

ext/json/generator/generator.c

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,28 @@ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data
7171

7272
static int usascii_encindex, utf8_encindex, binary_encindex;
7373

74+
#ifdef RBIMPL_ATTR_NORETURN
75+
RBIMPL_ATTR_NORETURN()
76+
#endif
77+
static void raise_generator_error_str(VALUE invalid_object, VALUE str)
78+
{
79+
VALUE exc = rb_exc_new_str(eGeneratorError, str);
80+
rb_ivar_set(exc, rb_intern("@invalid_object"), invalid_object);
81+
rb_exc_raise(exc);
82+
}
83+
84+
#ifdef RBIMPL_ATTR_NORETURN
85+
RBIMPL_ATTR_NORETURN()
86+
#endif
87+
static void raise_generator_error(VALUE invalid_object, const char *fmt, ...)
88+
{
89+
va_list args;
90+
va_start(args, fmt);
91+
VALUE str = rb_vsprintf(fmt, args);
92+
va_end(args);
93+
raise_generator_error_str(invalid_object, str);
94+
}
95+
7496
/* Converts in_string to a JSON string (without the wrapping '"'
7597
* characters) in FBuffer out_buffer.
7698
*
@@ -867,6 +889,17 @@ static inline int enc_utf8_compatible_p(int enc_idx)
867889
return 0;
868890
}
869891

892+
static VALUE encode_json_string_try(VALUE str)
893+
{
894+
return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
895+
}
896+
897+
static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
898+
{
899+
raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
900+
return Qundef;
901+
}
902+
870903
static inline VALUE ensure_valid_encoding(VALUE str)
871904
{
872905
int encindex = RB_ENCODING_GET(str);
@@ -886,7 +919,7 @@ static inline VALUE ensure_valid_encoding(VALUE str)
886919
}
887920
}
888921

889-
str = rb_funcall(str, i_encode, 1, Encoding_UTF_8);
922+
str = rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
890923
}
891924
return str;
892925
}
@@ -909,7 +942,7 @@ static void generate_json_string(FBuffer *buffer, struct generate_json_data *dat
909942
}
910943
break;
911944
default:
912-
rb_raise(rb_path2class("JSON::GeneratorError"), "source sequence is illegal/malformed utf-8");
945+
raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
913946
break;
914947
}
915948
fbuffer_append_char(buffer, '"');
@@ -957,10 +990,8 @@ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data
957990
char allow_nan = state->allow_nan;
958991
VALUE tmp = rb_funcall(obj, i_to_s, 0);
959992
if (!allow_nan) {
960-
if (isinf(value)) {
961-
rb_raise(eGeneratorError, "%"PRIsVALUE" not allowed in JSON", tmp);
962-
} else if (isnan(value)) {
963-
rb_raise(eGeneratorError, "%"PRIsVALUE" not allowed in JSON", tmp);
993+
if (isinf(value) || isnan(value)) {
994+
raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", tmp);
964995
}
965996
}
966997
fbuffer_append_str(buffer, tmp);
@@ -1008,7 +1039,7 @@ static void generate_json(FBuffer *buffer, struct generate_json_data *data, JSON
10081039
default:
10091040
general:
10101041
if (state->strict) {
1011-
rb_raise(eGeneratorError, "%"PRIsVALUE" not allowed in JSON", CLASS_OF(obj));
1042+
raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", CLASS_OF(obj));
10121043
} else if (rb_respond_to(obj, i_to_json)) {
10131044
tmp = rb_funcall(obj, i_to_json, 1, vstate_get(data));
10141045
Check_Type(tmp, T_STRING);
@@ -1036,10 +1067,6 @@ static VALUE generate_json_rescue(VALUE d, VALUE exc)
10361067
struct generate_json_data *data = (struct generate_json_data *)d;
10371068
fbuffer_free(data->buffer);
10381069

1039-
if (RBASIC_CLASS(exc) == rb_path2class("Encoding::UndefinedConversionError")) {
1040-
exc = rb_exc_new_str(eGeneratorError, rb_funcall(exc, rb_intern("message"), 0));
1041-
}
1042-
10431070
rb_exc_raise(exc);
10441071

10451072
return Qundef;
@@ -1537,10 +1564,11 @@ void Init_generator(void)
15371564
VALUE mExt = rb_define_module_under(mJSON, "Ext");
15381565
VALUE mGenerator = rb_define_module_under(mExt, "Generator");
15391566

1567+
rb_global_variable(&eGeneratorError);
15401568
eGeneratorError = rb_path2class("JSON::GeneratorError");
1569+
1570+
rb_global_variable(&eNestingError);
15411571
eNestingError = rb_path2class("JSON::NestingError");
1542-
rb_gc_register_mark_object(eGeneratorError);
1543-
rb_gc_register_mark_object(eNestingError);
15441572

15451573
cState = rb_define_class_under(mGenerator, "State", rb_cObject);
15461574
rb_define_alloc_func(cState, cState_s_allocate);

ext/json/lib/json/common.rb

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,23 @@ class CircularDatastructure < NestingError; end
143143
# :startdoc:
144144

145145
# This exception is raised if a generator or unparser error occurs.
146-
class GeneratorError < JSONError; end
146+
class GeneratorError < JSONError
147+
attr_reader :invalid_object
148+
149+
def initialize(message, invalid_object = nil)
150+
super(message)
151+
@invalid_object = invalid_object
152+
end
153+
154+
def detailed_message(...)
155+
if @invalid_object.nil?
156+
super
157+
else
158+
"#{super}\nInvalid object: #{@invalid_object.inspect}"
159+
end
160+
end
161+
end
162+
147163
# For backwards compatibility
148164
UnparserError = GeneratorError # :nodoc:
149165

test/json/json_generator_test.rb

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -250,17 +250,20 @@ def test_fast_state
250250
end
251251

252252
def test_allow_nan
253-
assert_raise(GeneratorError) { generate([JSON::NaN]) }
253+
error = assert_raise(GeneratorError) { generate([JSON::NaN]) }
254+
assert_same JSON::NaN, error.invalid_object
254255
assert_equal '[NaN]', generate([JSON::NaN], :allow_nan => true)
255256
assert_raise(GeneratorError) { fast_generate([JSON::NaN]) }
256257
assert_raise(GeneratorError) { pretty_generate([JSON::NaN]) }
257258
assert_equal "[\n NaN\n]", pretty_generate([JSON::NaN], :allow_nan => true)
258-
assert_raise(GeneratorError) { generate([JSON::Infinity]) }
259+
error = assert_raise(GeneratorError) { generate([JSON::Infinity]) }
260+
assert_same JSON::Infinity, error.invalid_object
259261
assert_equal '[Infinity]', generate([JSON::Infinity], :allow_nan => true)
260262
assert_raise(GeneratorError) { fast_generate([JSON::Infinity]) }
261263
assert_raise(GeneratorError) { pretty_generate([JSON::Infinity]) }
262264
assert_equal "[\n Infinity\n]", pretty_generate([JSON::Infinity], :allow_nan => true)
263-
assert_raise(GeneratorError) { generate([JSON::MinusInfinity]) }
265+
error = assert_raise(GeneratorError) { generate([JSON::MinusInfinity]) }
266+
assert_same JSON::MinusInfinity, error.invalid_object
264267
assert_equal '[-Infinity]', generate([JSON::MinusInfinity], :allow_nan => true)
265268
assert_raise(GeneratorError) { fast_generate([JSON::MinusInfinity]) }
266269
assert_raise(GeneratorError) { pretty_generate([JSON::MinusInfinity]) }
@@ -487,9 +490,13 @@ def test_invalid_encoding_string
487490
["\x82\xAC\xEF".b].to_json
488491
end
489492

490-
assert_raise(JSON::GeneratorError) do
491-
{ foo: "\x82\xAC\xEF".b }.to_json
493+
badly_encoded = "\x82\xAC\xEF".b
494+
exception = assert_raise(JSON::GeneratorError) do
495+
{ foo: badly_encoded }.to_json
492496
end
497+
498+
assert_kind_of EncodingError, exception.cause
499+
assert_same badly_encoded, exception.invalid_object
493500
end
494501

495502
class MyCustomString < String

0 commit comments

Comments
 (0)