proposal: encoding/json: include field name in unmarshal error messages for types that implement UnmarshalJSON
#71958
Labels
LibraryProposal
Issues describing a requested change to the Go standard library or x/ libraries, but not to a tool
Proposal
Milestone
Proposal Details
Problem context
The following example just outputs
panic: unhelpful error
which isn't useful in finding out which key in the JSON caused the problem, i.e "was itbar
orbaz
that caused the problem?" We only have access to the value bytes (no key name) so even if we wanted to write a better error message, we couldn't.panic: unhelpful error
Compare this with the built-in types where we get some helpful output ->
panic: json: cannot unmarshal number into Go struct field myType.bar of type string
because of the automatic logic behindjson.UnmarshalTypeError
(seeaddErrorContext
).panic: json: cannot unmarshal number into Go struct field myType.bar of type string
We can partially get our desired effect by returning
json.UnmarshalTypeError
ourselves but it doesn't allow for any extra context on why we failed to parse it. For example, what if the reason we failed to unmarshal was becauseStrawberries have at-least 200 seeds
but there is not place to add this context with the currentjson.UnmarshalTypeError
.panic: json: cannot unmarshal 1 into Go struct field myType.bar of type main.strawberry
Proposal
Wrap any error from
UnmarshalJSON
and include the field name context that generated the error.Another possibility is to extend
json.UnmarshalTypeError
to allow for additional custom errorcontext
which would work but not everyone is going to be as meticulous to always returnjson.UnmarshalTypeError
to get the benefits.I'm not writing Go everyday so there is probably a better strategy as well.
Related issues
The text was updated successfully, but these errors were encountered: