Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override errors in phoenix?

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.

like image 426
saa Avatar asked Feb 21 '15 00:02

saa


1 Answers

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.

like image 162
stephenmuss Avatar answered Oct 20 '22 17:10

stephenmuss