I build restful api (json) on phoenix. And I did not need the support of html.
How to override errors in phoenix? Example errors: - 500 - 404 when no route found and other.
For those who may have the same issues I had, there a couple of steps required to render JSON for 404 and 500 responses.
Firstly add render("404.json", _assigns)
and render("500.json", _assigns)
to your app's web/views/error_view.ex
file.
For example:
defmodule MyApp.ErrorView do
use MyApp.Web, :view
def render("404.json", _assigns) do
%{errors: %{message: "Not Found"}}
end
def render("500.json", _assigns) do
%{errors: %{message: "Server Error"}}
end
end
Then in your config/config.exs
file updated the default_format
to "json"
.
config :my_app, MyApp.Endpoint,
render_errors: [default_format: "json"]
Note that if your app is purely a REST api this will be fine, but be careful in the event you also render HTML responses as now by default errors will be rendered as json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With