Mapping errors back to Json request

Any best practice suggestions on providing exact offset (line, column) for errors coming from JSON input?

Appreciate this is a rather broad question; but any pointers such as “in order to map back to the original character that “causes” an error - have to parse json in phoenix like this; and then …” might help me start looking down the right track.

I have a very large JSON input; which goes through various rounds of validation - ranging from fairly manual; to ecto changesets. In the case of hitting errors; I would like to “as accurately as possible” inform the end user “this bit of your JSON needs to be changed.”

I will get as far as I can by validating the input JSON against a schema; but there are errors that can occur even if the JSON is structurally correct.

Having played around a bit; the fact that ecto returns errors in lists that include “offset” markers is already very helpful - knowing that it was the nth entry that causes an error means I could just use this offset.

Perhaps using the “implicit” ecto offset is the best way to approach? But any other suggestions would be most welcome!


FWIW, unless you’re returning the entire input JSON with the error then (line, column) may not be meaningful to the recipient. Imagine they’re generating that payload by calling Jason.encode(some_giant_data_structure).

Giving a JSON path to the offending part may be easier; then instead of learning that my JSON has an error on line 254 column 872 I’d learn that some.deeply[3].nested.thing.is_wrong

You want to return errors regarding business logic validation for a given payload.

Applications deal with business logic validations as below:

  • have a well defined error code for every business validation failure - MYAPP-100, MYAPP-101, etc
  • return description for a error code if requested
  • source json path(s) for an key where the validation is failing
  • most of the validation checks stop on encountering first error, this can be configurable based on input payload or url params

Sample error message:

  "message": "Description of what went wrong",
  "errors": [
      "code": "error_code"
      "description": "Error details description",
      "source": ["json_path1", "json_path2 if it involves multiple paths"]

You can look at json schema validations error message for a well defined format - JsonXema does that in elixir.

1 Like

Thanks for the pointers; agree that JSON path is a better approach.

1 Like