Phoenix do not take into consideration my custom errorView

I have defined a custom exception :


  defmodule UnkownBookError do
    @moduledoc false
    defexception message: "Unknown book id", plug_status: 404
  end

In ErrorView module I have added my custom error view func :

  def render("error.json", %{message: message}) do
    %{errors: %{detail: message}}
  end

But I always get this in the console :

[debug] Converted error Booking.BookHandler.UnkownBookError to 404 response

and I get a text response in Postamn instead of JSON :

What I’m missing here ?

Thanks

1 Like
  1. What headers do you have? Have you sent Accept: application/json?
  2. Matching by template name is invalid. In case of 404, the template is the following: 404.json, not error.json.
  3. The second parameter is not an exception, but assigns. The exception could be found in assigns.reason.

If you want generic handler for JSON format:

def render(<<_::binary-size(3)>> <> ".json" = template, assigns) do
  %{
    error: Phoenix.Controller.status_message_from_template(template),
    description: Exception.message(assigns.reason)
  }
end

but don’t show a message from all exceptions, as they may contain not public information

3 Likes

Thanks a lot @fuelen , so I get that “error_view.ex” is responsible from rendring theese errors, so what is the purpose of “fallback_controller.ex” ?

For example in my file “fallback_controller.ex” I have only :

I’m not defining how Forbidden (403 status) will be handled, and If I try a forbidden action I get the correct error :

1 Like

action_fallback is about consolidating common error return values (of your business logic) and how they’re transformed to http responses (it’s about data).

MyAppWeb.ErrorView is a view, so it’s about transforming elixir data into json/html/whatever format your http response should be formatted in. This one specifically is about rendering responses for the various http error codes.

1 Like