Gracefully handle 404s and other errors in Phoenix using Plug.ErrorHandler

amos-kibet

amos-kibet

Created 6 hours ago

Instead of letting your Phoenix app crash with ugly errors, add this clean error handler:

#lib/myapp_web/router.ex
use Plug.ErrorHandler

@impl Plug.ErrorHandler
def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
  has_message = Map.has_key?(reason, :message)
  
  json(conn, %{
    "error" => [%{
      "code" => "generic", 
      "message" => if has_message, do: reason.message, else: "Problem occurred"
    }]
  })
end

Now your app returns a nice JSON response instead of raising errors, and the server won’t crash. You can also return HTML with a generic 404 page 💪

You can read more on hexdocs: https://hexdocs.pm/plug/Plug.ErrorHandler.html