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.
Last Post!
Exadra37
I showed it to you in my first post:
This file can be found in your app web views folder.
Basically ti’s overriding the render/2 function called to render the error templates for each error status code that is defined in the templates folder.
It also customizes the template_not_found/2 to return the Json error.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









