dimitarvp
Plug.ErrorHandler: how to use to return JSON errors?
I’m looking into returning JSON errors from an API app. I know the specs dictate you must always return HTML on certain error codes but I want to circumvent that because I’ll have complete control both on the calling side and the service itself. Plus the service will send logs and telemetry and I want errors to be machine-parseable.
I tried a few things after searching the forum but I couldn’t manage to make any of them work.
Then I stumbled upon Plug.ErrorHandler — Plug v1.20.2. Call me stupid but I have no clue how to use it?
So as a start I want all 404s and 500s to be wrapped with a JSON key errors in an object, returned alongside a 404 and 500 status.
Is this possible using Plug.ErrorHandler? If so, how exactly?
Most Liked
dimitarvp
Nope, that didn’t work. ![]()
Hitting a non-existent endpoint with curl:
HTTP/1.1 404 Not Found
cache-control: max-age=0, private, must-revalidate
content-length: 1333
content-type: text/markdown; charset=utf-8
date: Mon, 12 Apr 2021 16:33:02 GMT
server: Cowboy
# Phoenix.Router.NoRouteError at POST /does_not_exist
Exception:
** (Phoenix.Router.NoRouteError) no route found for POST /does_not_exist (MyAppWeb.Router)
# <snip>
And it’s returning markdown text? Why?
I am still trying to understand how do I just intercept ALL errors and wrap them in keys in a resulting JSON object.
Exadra37
Sorry for not having given you a good solution ![]()
But did you try the Error view approach? I think that one should work ![]()
Because you are in development mode. Go to config/dev.exs and set debug_errors to false.









