-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add context to errors in JSON.mapping #5932
Add context to errors in JSON.mapping #5932
Conversation
I like this, but the "exceptions are pretty rare" argument doesn't convince me. Imagine an http server. I can bombard you with invalid json and then you'll waste resources both raising and building that exception message. But since raising is already slow, I don't think there's a fix for this (this is why Go returns an error instead of raising, it's always cheap). |
spec/std/json/mapping_spec.cr
Outdated
JSONPerson.from_json(%({"age": 30})) | ||
end | ||
ex.location.should eq({1, 1}) | ||
end | ||
|
||
it "raises if not an object" do | ||
ex = expect_raises JSON::MappingError, "Expected begin_object but was string at 1:1\n parsing StrictJSONPerson at 0:0" do |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you format this with a heredoc to make this readable?
* Add context to errors in JSON.mapping * fixup! Add context to errors in JSON.mapping
Errors from JSON parse methods generated by
JSON.mapping
are difficult to debug. The message only tells about the immediate error encountered byJSON::PullParser
, for exampleExpected int but was string
. At least the source location is attached, but that makes it still quite hard to figure out, what exactly the parser was doing and parsing which object failed, especially in large JSON structures (such as theindex.json
produced by the docs generator).This PR adds some context to errors raised by
.parse_json
by adding the name of the class and property (if available) that is being parsed.These errors are wrapped, so each level of JSON data is unwrapped and can be followed. It's roughly comparable to a stack trace.
This exception hierarchy can probably get pretty large with highly nested JSON structures. I'm not sure if the outer contexts are really that useful.
This deep wrapping could be removed and only the significant innermost scope would get wrapped, adding the most important context information.
Obviously, this entire context feature adds some additional overhead to the JSON mapping parser. Exceptions are usually pretty rare, so it shouldn't matter much. In the case it happens, the additional debug info should be worth it.