Open mudrz opened 2 years ago
This would be very helpful! I'm also encountering this as I build out an API client.
It's possible to get better error reporting by catching the exception and printing its contents:
type t = {
count: int;
name: string;
}
[@@deriving yojson]
let yojson_result yojson of_yojson =
try Ok (of_yojson yojson)
with Ppx_yojson_conv_lib__Yojson_conv.Of_yojson_error (exn, node) ->
Error (`YojsonError (exn, node))
let json = Yojson.Safe.from_string {json| {"name": "test"} |json}
let print_yojson_err exn node =
let str_exn = Printexc.to_string exn in
let node_str = Yojson.Safe.pretty_to_string node in
Printf.printf "YojsonError: %s, %s\n" str_exn node_str
let () =
match yojson_result json t_of_yojson with
| Ok _ -> ()
| Error (`YojsonError (exn, node)) -> print_yojson_err exn node
will print out
YojsonError: Failure("yourfile.ml.t_of_yojson: the following record elements were undefined: count"), { "name": "test" }
Though sometimes the errors aren't that great. E.g. changing the json data to
let json = Yojson.Safe.from_string {json| {"count": "2", "name": "test"} |json}
gives the rather unhelpful error message
YojsonError: Failure("int_of_yojson: integer needed"), "2"
when I run
dune exec ...
(even with--verbose
) if the json format differs from the defined type I get errors like:Is it possible somehow to get more details for the error, for example: