wisp icon indicating copy to clipboard operation
wisp copied to clipboard

Improve invalid JSON body error message

Open markholmes opened this issue 8 months ago • 1 comments

When sending an HTTP request with an invalid JSON body and attempting using wisp.require_json, it would be helpful to have an error message with a bit more information. The current behavior is a 400: Bad Request response from the server with no error message or reason as to why.

https://hexdocs.pm/wisp/wisp.html#require_json

If the body cannot be parsed successfully then an empty response with status code 400: Bad request will be returned to the client.

Just as an example, this is what Flask does:

curl localhost:4000/banana -d '{"foo": "foo","bar":"bar",}' -H 'content-type:application/json'

Caught HTTPException: 400 Bad Request: Failed to decode JSON object: trailing comma is not allowed: line 1 column 26 (char 25)

Unsure if this is possible but it might be helpful to others in the future 😅

markholmes avatar Mar 30 '25 22:03 markholmes

Hey hey! Yes I think you've a good point here. It would be useful to give more detailed error messages to the user for these middleware errors, but the current Empty variant doesn't give enough detail for the programmer's "default responses" to distinguish between JSON parse errors and other errors. At most you can get Empty + status 400 + content-type: application/json.

Perhaps we should replace the Empty with some sort of generic error variant which holds more information. An early thought of mine is that it could be based on application/problem+json (RFC 7807).

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json

{
  "type": "https://example.com/probs/invalid-json",
  "title": "Invalid JSON",
  "status": 400,
  "detail": "Unexpected token at position 15"
}

Then the default responses could use that information (and we can specialise the concept to errors specifically rather than being able to transform any response). Note I've shown the RFC JSON representation here, but the programmer could render any format they want from the status code, the response headers, and the new type and title and detail fields.

Need to think if this is enough, or if there's other options that would be good here.

We'd still want programmers to construct their own errors responses for failures within the application domain.

lpil avatar Apr 02 '25 10:04 lpil