janestreet / ppx_yojson_conv

[@@deriving] plugin to generate Yojson conversion functions
MIT License
58 stars 8 forks source link

get parsing errors details? #12

Open mudrz opened 2 years ago

mudrz commented 2 years ago

when I run dune exec ... (even with --verbose) if the json format differs from the defined type I get errors like:

!Fatal error: exception Ppx_yojson_conv_lib__Yojson_conv.Of_yojson_error(_, _)
Raised at Ppx_yojson_conv_lib__Yojson_conv.of_yojson_error in file "yojson_conv.ml", line 57, characters 34-80
Called from Dune__exe__Json.user_of_yojson.(fun).iter in file "..."

Is it possible somehow to get more details for the error, for example:

dylanirlbeck commented 1 year ago

This would be very helpful! I'm also encountering this as I build out an API client.

hypirion commented 1 week ago

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"