GUIDES
GUIDESDOCS

Exceptions

You can handle exception with rescue_from DSL like this:

rescue_from Unauthorized do
  conn
  |> put_status(401)
  |> text("Unauthorized")
end
rescue_from [MatchError, UndefinedFunctionError] do
  conn
  |> put_status(500)
  |> text("Run time error")
end
rescue_from :all do
  conn
  |> put_status(500)
  |> text("Server Error")
end

It is compiled to:

def call(conn, opts) do
  try do
    super(conn, opts)
  rescue
    Unauthorized ->
    conn |> put_status(401) |> text("Unauthorized")
  end
end
def call(conn, opts) do
  try do
    super(conn, opts)
  rescue
    [MatchError, UndefinedFunctionError] ->
    conn |> put_status(500) |> text("Run time error")
  end
end
def call(conn, opts) do
  try do
    super(conn, opts)
  rescue
    _ ->
    conn |> put_status(500) |> text("Server Error")
  end
end

Use rescue_from/3 if you need the exception variable.

rescue_from [MatchError, UndefinedFunctionError], as: e do
  e |> IO.inspect
  
  conn 
  |> put_status(500)
  |> text("Run time error")
end

and it is compiled to:

def call(conn, opts) do
  try do
    super(conn, opts)
  rescue
    e in [MatchError, UndefinedFunctionError] ->
      e |> IO.inspect
  
      conn 
      |> put_status(500)
      |> text("Run time error")
  end
end