If I send an invalid request to a JSON API endpoint (with JSON body that cannot be decoded). Phoenix serves the 500.html.eex
page.
Is there a way to reply with a JSON error when the Content-Type
is set to JSON?
If I send an invalid request to a JSON API endpoint (with JSON body that cannot be decoded). Phoenix serves the 500.html.eex
page.
Is there a way to reply with a JSON error when the Content-Type
is set to JSON?
Content-Type
is the header for telling the server the content of the request body. Accept
is the header you want to set to tell the server how to respond. The accepts plug does the content negotation
Yes, I wasn’t clear sorry. I meant both headers set to JSON but the body is invalid.
The server tries to send the 500.html.eex
page, but it fails with protocol Jason.Encoder not implemented for {:safe, ["<!DOCTYPE html>\...
I tried creating a 500.json.eex
but phoenix is not picking it up
That sounds like it actually tries to send json (so json is the format negotiated), but something rendered the 500.html
specifically.
It seems phoenix is serving it directly without hitting my error handling code or even the controller.
Did you add json to the accepted formats in your endpoint’s render_errors
configuration?
https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#module-runtime-configuration
Yes, but apparently def render("500.html", assigns)
is called in my view, regardless of the headers. I can look at assigns.req_headers
to return a JSON response.
My bad, actually it was passing "400.json"
and I didn’t have that one which thrown a second error with 500.html
.
Makes sense. A parsing error in the request would trigger a 4xx error not a 5xx one.