Skip to main content
Axum provides multiple ways to handle errors in your application. Understanding these patterns will help you build robust web services.

Basic error handling

The simplest way to handle errors is using Result types:
Both Ok and Err variants must implement IntoResponse.

Custom error types

Create application-specific error types that implement IntoResponse:

Using the ? operator

Convert errors automatically with From implementations:

Real-world error handling

A complete example with proper error handling:

Error logging with middleware

Log errors without exposing details to clients:

HandleErrorLayer for middleware

Handle errors from Tower middleware:

Extractor rejections

Customize how extractor failures are handled:

Result type aliases

Simplify handler signatures with type aliases:

Error best practices

Never leak sensitive information in error messages:
Return the correct HTTP status code for each error type:
  • 400 Bad Request - Invalid input
  • 401 Unauthorized - Missing or invalid authentication
  • 403 Forbidden - Authenticated but not authorized
  • 404 Not Found - Resource doesn’t exist
  • 409 Conflict - Request conflicts with current state
  • 422 Unprocessable Entity - Valid syntax but semantic errors
  • 500 Internal Server Error - Server errors
  • 503 Service Unavailable - Temporary unavailability

Next steps

Middleware

Use middleware for error logging and handling

Responses

Learn more about response types