quda
Phoenix - returning custom 500 (Internal Server Error). How to?
I need to return a custom error message (json) for Internal Server Error.
The message is needed for explaining some error causes such as: corrupt file, internal path not found, bad json, python script execution error etc.
The 500 error would be raised in certain places in my Phoenix web API code when such upstream errors/exceptions occurs.
In the official doc is not clear how exactly to do this.
Thanks for help!
Marked As Solved
mcrumm
Review the Custom Exceptions section of that same guide.
You will need a defimpl Plug.Exception if you want your exception to be rendered as an HTTP response through Plug.
If you want to render your custom error in production, you will also need to add a pattern match to the render/2 function on your ErrorView. To ensure this is working correctly, you may want to set debug_errors: false on your Endpoint config in
dev.exs. ![]()
Edits: typos
Also Liked
quda
Thanks, I eventually managed to do it with defimpl.
I’m writing here the solution, it might help others with similar issues:
In the myapp_web.ex:
defmodule Myapp.Customerror do
defexception [:message]
end
defimpl Plug.Exception, for: Myapp.Customerror do
def status(_exception), do: 500
end
error_view.ex:
def render("500.json", %{conn: conn}) do
%{error: conn.assigns.reason.message}
end
.Finally, in my code:
raise Myapp.Customerror, "My custom message"
Cheers,
T.
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









