Plug v1.5.0 Plug.ErrorHandler View Source

A module to be used in your existing plugs in order to provide error handling.

defmodule AppRouter do
  use Plug.Router
  use Plug.ErrorHandler

  plug :match
  plug :dispatch

  get "/hello" do
    send_resp(conn, 200, "world")
  end

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

Once this module is used, a callback named handle_errors/2 should be defined in your plug. This callback should accept a connection and a map containing:

  • the exception kind (:throw, :error or :exit),
  • the reason (an exception for errors or a term for others)
  • the stacktrace

After the callback is invoked, the error is re-raised.

It is advised to do as little work as possible when handling errors and avoid accessing data like parameters and session, as the parsing of those is what could have led the error to trigger in the first place.

Also notice that these pages are going to be shown in production. If you are looking for error handling to help during development, consider using Plug.Debugger.

Note: If this module is used with Plug.Debugger, it must be used after Plug.Debugger.