Plug.ErrorHandler: how to use to return JSON errors?

Please bear in mind that all what I am about to suggest is from the top of my mind, therefore not tested, and may be wrong, but hey it doesn’t hurt for you to give it a try :slight_smile:

  def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
    send_resp(conn, conn.status, "Something went wrong")
  end

If I am not mistake the above will override the call to the Error view at lib/yourapp_web/views/error_view.ex.

I think that this will return it in json:

# You may need to use the Jason library if returning only the map doesn't work.
# You also want to put the `application/json` header in the `conn`
send_resp(conn, conn.status,%{error: conn.status, message:  "Something went wrong"})

Maybe you can simplify the above to use in your router:

# file: lib/yourapp_web/router.ex
  pipeline :api do
    plug :accepts, ["json"],
    plug :handle_errors
  end

  # you may need to pattern match in `conn.status` to make this work
  def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
    # You may need to use the Jason library if returning only the map doesn't work.
    # You also want to put the `application/json` header in the `conn`
    send_resp(conn, conn.status,%{error: conn.status, message:  "Something went wrong"})
  end

EDIT: On a second though I think this isn’t reflecting the intended use from the Plug.ErrorHandler

An Alternative that you can try is to change the Error view to always return a JSON object:

defmodule YourAppWeb.ErrorView do
  use YourAppWeb, :view

  require Logger

  # If you want to customize a particular status code
  # for a certain format, you may uncomment below.
  def render(template, assigns) do
    _json_error(template, assigns)
  end

  # By default, Phoenix returns the status message from
  # the template name. For example, "404.html" becomes
  # "Not Found".
  def template_not_found(template, assigns) do
    _json_error(template, assigns)
  end

  defp _json_error(template, assigns) do

    Logger.info("Error template: #{template}")
    # render("500.html", assigns)
    
    # I am not sure, but I think you can just return a Map, otherwise just try to use the Jason library.
    %{
      error: 400, # You need to extract it from assigns or template name
      maessage: "Whoops!"
    }

  end
  
end