quinnj / JSON3.jl

Other
214 stars 47 forks source link

Error Handling Fields #268

Open onetonfoot opened 1 year ago

onetonfoot commented 1 year ago

Hey, when working with JSON3 and StructTypes, I've noticed that the error messages received when passing incorrect data lack clarity, specifically in mentioning field names.

Here's a small example:

using StructTypes, JSON3

struct X
    x::Int
    y::Float64
    z::String
end

StructTypes.StructType(::Type{X}) = StructTypes.Struct()

valid_bad_json = """ { "x": 1, "y": 2, "z": 1 } """
JSON3.read(valid_bad_json, X)

# ERROR: ArgumentError: invalid JSON at byte position 25 while parsing type String: ExpectedOpeningQuoteChar
# { "x": 1, "y": 2, "z": 1 } 

StructTypes.constructfrom(X, JSON3.read(valid_bad_json))

# ERROR: MethodError: no method matching String(::Int64)

The error message doesn't specify which field caused the error. The issue becomes even more challenging with larger or nested structs. For improved developer experience, I'd love to see error messages that indicate:

  1. The name of the field causing the error.
  2. The specific type of error that occurred.

Libraries like zod or pydantic provide excellent examples of detailed error messages that include the exact path to the offending field and the nature of the error.

When following the happy path everything works smoothly and the packages are a joy to use!