Predictable Error Model in Axum

Understand how Axum turns handler errors into HTTP responses and why that model is predictable.

When you build a web service, errors are a fact of life. A database might be down, a user might send a bad ID, or a file might be missing. Every web framework needs a way to take those internal problems and turn them into sensible HTTP responses. Axum's approach to this is one of its strengths: it uses Rust's own Result type to make error handling explicit and predictable.

This page explains exactly how that works. You will see several complete examples, starting with the simplest possible handler and building up to custom error types that give you full control over what clients receive.

The Basic Idea of Axum's Error Model

In Axum, a handler is an async function that receives some input (extractors) and returns something that can become an HTTP response. That "something" is called an IntoResponse type. Strings, status codes, JSON values, and even tuples like (StatusCode, String) all implement IntoResponse.

When a handler can fail, you make it return a Result. The Ok variant contains the success value; the Err variant contains the error value. Axum's rule is simple:

  • The success type must implement IntoResponse.
  • The error type must also implement IntoResponse.

Because both the good and bad paths produce an IntoResponse, Axum always knows how to convert the final value into an HTTP response. There is no separate "exception handling" layer, no hidden control flow, and no way to forget to handle an error. The compiler checks everything.

Result is Rust's Standard Tool:

Result<T, E> is Rust's built-in type for operations that can succeed or fail. T is the success value, E is the error value. The ? operator used inside a function that returns Result will immediately return the Err value if something fails. Axum leans on this familiar pattern instead of inventing something new.

That is the entire model in one paragraph. Now we will see it in practice with progressively more realistic examples.

Returning a Simple Result from a Handler

Start with the smallest possible error‑aware handler. The following function returns Result<String, StatusCode>. On success, it sends a 200 OK with a text body. On failure, it sends a bare status code.

use axum::{extract::Path, routing::get, Router, http::StatusCode};
async fn divide_by_two(Path(number): Path<String>) -> Result<String, StatusCode> {
    match number.parse::<i32>() {
        Ok(n) if n % 2 == 0 => Ok(format!("{n} is even")),
        Ok(_) => Err(StatusCode::BAD_REQUEST),   // odd number: client error
        Err(_) => Err(StatusCode::BAD_REQUEST),  // not a number: client error
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/even/{number}", get(divide_by_two));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The handler extracts number from the path with Path<String>. A bare String parameter would not do this: a bare String is a body extractor - it consumes the whole request body and requires valid UTF-8. Only Path<String> reads a path segment. It then tries to parse that string as an integer. If parsing succeeds and the number is even, we return Ok with a message. Otherwise we return Err with StatusCode::BAD_REQUEST.

Run this server and test it with a tool like curl:

curl http://localhost:3000/even/10
# Response: 200 OK, body "10 is even"
curl http://localhost:3000/even/7
# Response: 400 Bad Request, empty body
curl http://localhost:3000/even/abc
# Response: 400 Bad Request, empty body

The important observation is that returning Err(StatusCode::BAD_REQUEST) automatically produced a 400 response. You did not write any special catch block or call any response builder for the error case. The StatusCode type implements IntoResponse, so Axum can use it as the error value directly.

Everything Compiles and Behaves As Expected:

If you see the responses described above, your error handling is working correctly. The compiler has already verified that StatusCode can be turned into a response, and Axum has done the conversion at runtime.

What "Predictable" Actually Means

In many web frameworks, errors are thrown as exceptions or returned as values that the framework might or might not catch. You often have to remember to register a global error handler, or you risk sending a generic 500 page for every failure. Worse, some frameworks silently swallow certain error types.

Axum's model is predictable because:

  1. The signature tells the truth. If a handler returns Result<T, MyError>, you immediately know that MyError will become the response when something goes wrong.
  2. The compiler enforces conversion. MyError must implement IntoResponse; otherwise the code will not compile. You cannot accidentally leave an error type unconvertible.
  3. There is one conversion path. When Axum runs a handler, it calls into_response() on the Ok value or the Err value. Nothing else happens behind the scenes.
  4. All errors are handled. Because every error type is an IntoResponse, there is no "unhandled error" category. The framework can always produce a response.

This predictability reduces mental overhead. You spend less time wondering "what happens if this fails?" and more time building the actual logic.

Using a Custom Error Type for Full Control

Using StatusCode as an error type is quick, but it gives you only a status code, no body or additional headers. Real APIs need to send structured error information, like a JSON object containing an error code and a message. To achieve that, you define your own error type and implement IntoResponse for it.

Here is a common pattern: define an enum that lists all the ways your API can fail, then implement IntoResponse to map each variant to a specific HTTP response.

use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
#[derive(Debug)]
enum ApiError {
    NotFound,
    BadRequest(String),
    InternalServerError,
}
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::NotFound => (StatusCode::NOT_FOUND, "Resource not found".to_string()),
            ApiError::BadRequest(detail) => (StatusCode::BAD_REQUEST, detail),
            ApiError::InternalServerError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
async fn get_user(Path(id): Path<u64>) -> Result<Json<serde_json::Value>, ApiError> {
    if id == 0 {
        return Err(ApiError::BadRequest("id must be positive".to_string()));
    }
    // Simulate a database lookup that fails
    if id == 999 {
        return Err(ApiError::NotFound);
    }
    // Simulate an unexpected failure
    if id == 500 {
        return Err(ApiError::InternalServerError);
    }
    Ok(Json(json!({
        "id": id,
        "name": "Alice"
    })))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Let's walk through the important parts:

  • ApiError is a plain Rust enum with three variants.
  • We implement IntoResponse for ApiError. The into_response method matches on the variant, decides what status code and message to use, then builds a response. The (StatusCode, Json(...)) tuple already implements IntoResponse, so we can call .into_response() on it.
  • The handler get_user returns Result<Json<serde_json::Value>, ApiError>. On success, it returns a Json response. On failure, it returns the appropriate ApiError variant using Err(...). The ? operator could also be used if some inner function returned Result<_, ApiError>.

Test the endpoints:

curl http://localhost:3000/users/0
# 400 Bad Request, body {"error":"id must be positive"}
curl http://localhost:3000/users/999
# 404 Not Found, body {"error":"Resource not found"}
curl http://localhost:3000/users/500
# 500 Internal Server Error, body {"error":"Something went wrong"}
curl http://localhost:3000/users/42
# 200 OK, body {"id":42,"name":"Alice"}

This gives you total control over the error response format. Clients receive consistent JSON error bodies, which makes their life easier.

The ? Operator Needs From, Not Display:

The ? operator converts one error type into another with From, so what it needs is a From implementation into your handler's error type - not Display. Display becomes necessary when something actually prints or logs the error, or when you convert it into anyhow::Error (which requires the source error to implement Display). In the example above we avoided ? and returned Err directly, so neither was needed. The next example shows how to add Display using the thiserror crate.

Reducing Boilerplate with thiserror

Manually implementing Display for an error enum can become repetitive, especially when you have many variants. The thiserror crate provides a derive macro that generates the Display implementation from a simple attribute. It also lets you automatically convert from other error types using #[from].

Add thiserror to your Cargo.toml:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
thiserror = "2"

Now rewrite the error enum:

use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
enum ApiError {
    #[error("resource not found")]
    NotFound,
    #[error("bad request: {0}")]
    BadRequest(String),
    #[error("internal server error")]
    InternalServerError,
}
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::NotFound => (StatusCode::NOT_FOUND, "Resource not found".to_string()),
            ApiError::BadRequest(detail) => (StatusCode::BAD_REQUEST, detail),
            ApiError::InternalServerError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
async fn get_user(Path(id): Path<u64>) -> Result<Json<serde_json::Value>, ApiError> {
    if id == 0 {
        return Err(ApiError::BadRequest("id must be positive".to_string()));
    }
    // ... same as before
}

The #[derive(Error)] macro generates a Display implementation for each variant according to the #[error("...")] strings. This allows you to use ? with functions that return Result<_, ApiError>, and it also enables logging with tracing or log crates. The behavior of the HTTP response is unchanged because we still implement IntoResponse manually.

You Can Also Use anyhow for Rapid Prototyping:

The anyhow crate provides a flexible error type that can wrap any other error. Some developers use anyhow::Result<T> in handlers during early development. However, anyhow::Error does not implement IntoResponse by default, so you must convert it to something that does before returning from the handler. A common pattern is to define a small wrapper that implements IntoResponse and converts anyhow::Error into a 500 with a generic message.

Propagating Errors with the ? Operator

In real applications, your handler will call other functions that can fail. Instead of writing match on every call, you can use ? to automatically return the error from the handler. For this to work, the inner function's error type must be convertible into the handler's error type.

Here is an example where we simulate a database query that returns Result<User, DbError>, and we map DbError into ApiError using a From implementation or map_err.

First, define a simple DbError and a From conversion:

#[derive(Debug, thiserror::Error)]
enum DbError {
    #[error("connection failed")]
    Connection,
}
impl From<DbError> for ApiError {
    fn from(err: DbError) -> Self {
        match err {
            DbError::Connection => ApiError::InternalServerError,
        }
    }
}
async fn fetch_user_from_db(id: u64) -> Result<String, DbError> {
    if id > 100 {
        Err(DbError::Connection)
    } else {
        Ok(format!("user {id}"))
    }
}

Now the handler can use ?:

async fn get_user(Path(id): Path<u64>) -> Result<Json<serde_json::Value>, ApiError> {
    if id == 0 {
        return Err(ApiError::BadRequest("id must be positive".to_string()));
    }
    let name = fetch_user_from_db(id).await?; // DbError is converted to ApiError via From
    Ok(Json(json!({ "id": id, "name": name })))
}

The ? operator sees a Result<String, DbError>. Since ApiError implements From<DbError>, Rust automatically converts the error type, and the ? returns Err(ApiError::InternalServerError) from the handler. No map_err call is needed because of the From impl.

If you do not want to implement From, you can use map_err:

let name = fetch_user_from_db(id)
    .await
    .map_err(|_| ApiError::InternalServerError)?;

Either approach is fine. The From impl is more reusable, while map_err is more local and explicit.

Handling Many Error Types by Converging on One

A handler often needs to call functions that return different error types (database errors, serialization errors, network errors). You cannot return multiple different error types directly; the handler's signature must pick one. The solution is to define a single application error type and implement From for every underlying error type you need to convert.

Here is a slightly larger example that shows a handler calling two functions with different error types:

use axum::{routing::get, Router, http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
enum ApiError {
    #[error("bad request: {0}")]
    BadRequest(String),
    #[error("internal server error")]
    Internal,
}
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            ApiError::BadRequest(detail) => (StatusCode::BAD_REQUEST, detail),
            ApiError::Internal => (StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string()),
        };
        (status, Json(json!({ "error": msg }))).into_response()
    }
}
// Simulated error types
#[derive(Debug, thiserror::Error)]
enum DbError {
    #[error("db failed")]
    DbFailed,
}
#[derive(Debug, thiserror::Error)]
enum ParseError {
    #[error("parse failed")]
    ParseFailed,
}
impl From<DbError> for ApiError {
    fn from(_: DbError) -> Self { ApiError::Internal }
}
impl From<ParseError> for ApiError {
    fn from(_: ParseError) -> Self { ApiError::BadRequest("invalid input".to_string()) }
}
async fn read_from_db() -> Result<String, DbError> {
    Err(DbError::DbFailed)
}
async fn parse_input() -> Result<i32, ParseError> {
    Err(ParseError::ParseFailed)
}
async fn combined_handler() -> Result<String, ApiError> {
    let db_value = read_from_db().await?;   // DbError -> ApiError
    let number = parse_input().await?;       // ParseError -> ApiError
    Ok(format!("{db_value} {number}"))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(combined_handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Both ? uses work because ApiError has From implementations for DbError and ParseError. This pattern scales well: add a new error type, implement From, and use ? everywhere.

Beware of Forgetting From Implementations:

If you try to use ? with an error type that does not convert into your handler's error type, the compiler will emit an error like the trait bound ApiError: From<DbError> is not satisfied. This is the compiler saving you from a runtime surprise. Do not ignore such errors by using unwrap or expect on Result; that will panic, and by default a handler panic drops the connection with no response at all (a 500 only comes from CatchPanicLayer). Instead, add the missing From impl or use map_err to convert explicitly.

Returning Errors Without Defining a Custom Type

Sometimes you want a quick error response without creating an enum. Axum lets you use tuples as error types, as long as the tuple implements IntoResponse. The most common tuple is (StatusCode, String):

use axum::http::StatusCode;
async fn handler() -> Result<&'static str, (StatusCode, String)> {
    let input_is_valid = false; // pretend this came from validation logic
    if input_is_valid {
        Ok("success")
    } else {
        Err((StatusCode::BAD_REQUEST, "bad input".to_string()))
    }
}

You can also use (StatusCode, Json<serde_json::Value>) for JSON errors:

use axum::{http::StatusCode, Json};
use serde_json::json;
async fn handler() -> Result<&'static str, (StatusCode, Json<serde_json::Value>)> {
    Err((
        StatusCode::NOT_FOUND,
        Json(json!({"error": "not found"})),
    ))
}

This is convenient for small projects, but as your API grows, defining a dedicated error type gives you a single place to manage error responses and keeps handler signatures shorter.

What Happens with Panics?

Axum's error model covers Result-based errors. Panics are a different mechanism: they unwind the stack and are not part of the type system. By default, axum does not catch a panic in a handler and does not turn it into a 500 response. The panic unwinds that request's task, the connection is dropped, and the client gets no response at all. A 500 only appears if you opt in with tower_http::catch_panic::CatchPanicLayer (feature catch-panic in tower-http):

use tower_http::catch_panic::CatchPanicLayer;
let app = Router::new()
    .route("/", get(handler))
    .layer(CatchPanicLayer::new());

Relying on panics for normal error handling is not recommended because:

  • Panics do not carry structured information; the client sees only a generic 500.
  • Panics are slower than returning Result.
  • Panics can leave resources in an inconsistent state if not handled carefully.

Treat panics as bugs, not as expected failures. Use Result for anything that can fail due to user input, missing resources, or external services.

Do Not Use panic! for Validation Errors:

A common beginner mistake is to call .unwrap() or panic! when an extractor or database call fails. By default that does not even produce a 500 response - the connection is dropped with no response - even when the real cause is a 400-level client error. Always prefer returning a Result with an appropriate status code.

Multiple Ways to Handle Errors - A Quick Comparison

You have now seen several approaches. Here is a summary of when to choose each one:

ApproachWhen to useProsCons
StatusCode as error typeVery simple APIs, prototypesMinimal codeNo error body, limited to status only
(StatusCode, String) or (StatusCode, Json) tupleQuick JSON error responsesSlightly more informative than bare statusStill ad‑hoc, repetitive across handlers
Custom enum with IntoResponseProduction APIs with structured errorsFull control, consistent format, reusableRequires writing some boilerplate (reduced by thiserror)
anyhow::Error with a wrapperEarly development, internal toolsVery flexible, low frictionLess type safety; must convert to IntoResponse

Each approach follows the same underlying rule: the error type must implement IntoResponse. Pick the one that matches your project's stage and needs.

Common Misconceptions About Axum's Error Model

  1. "I can return Result<T, Box<dyn Error>> and Axum will handle it."
    No - there is no IntoResponse implementation for Box<dyn Error> in axum, so a handler returning Result<T, Box<dyn Error>> does not compile. The error type must implement IntoResponse itself. Convert the error first - for example with .map_err(|e| ApiError::Internal) or by defining a custom error type with a From<Box<dyn Error>> conversion - and use a custom error type whenever you need proper status codes for client errors. (The same applies to anyhow::Error: it does not implement IntoResponse either, so it needs a wrapper, as noted above.)

  2. "The Result itself needs to implement IntoResponse."
    Not exactly. Axum looks at the Ok and Err types individually. The Result wrapper is just a signal that the handler can fail.

  3. "I must write a global error handler for every error."
    With Axum's type‑driven approach, you do not need a central error handler for normal handler errors. Each error type knows how to respond. A global error handler might be used for middleware errors or panics, but that is a separate topic.

  4. "If I use ?, the error will automatically become a 500."
    Only if your error type's IntoResponse says so. The ? operator just returns the error; the status code comes from IntoResponse. You can make any error produce a 400 or 404 if you implement it that way.

  5. "Returning Result<(), Infallible> is a good way to indicate a handler cannot fail."
    Infallible is a type that can never be constructed, so it is useful as a placeholder error type when you want to write handlers that never return Err. However, if you later need to add real error handling, you will have to change the signature. It is often simpler to return the success type directly instead of Result<T, Infallible>.

Putting It All Together: A Complete Mini API

Let's combine everything into one example that demonstrates a small REST API for fetching a user by ID. It uses a custom error enum, thiserror, ? propagation, and a consistent JSON error body.

use axum::{
    extract::Path,
    routing::get,
    Router,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
enum ApiError {
    #[error("user not found")]
    UserNotFound,
    #[error("invalid user id: {0}")]
    InvalidId(String),
    #[error("database connection failed")]
    DatabaseError,
}
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::UserNotFound => (StatusCode::NOT_FOUND, "User not found".to_string()),
            ApiError::InvalidId(detail) => (StatusCode::BAD_REQUEST, detail),
            ApiError::DatabaseError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal server error".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
// Simulated database function
async fn get_user_from_db(id: u64) -> Result<String, ApiError> {
    match id {
        0 => Err(ApiError::InvalidId("id cannot be zero".to_string())),
        1 => Ok("Alice".to_string()),
        2 => Ok("Bob".to_string()),
        _ => Err(ApiError::UserNotFound),
    }
}
async fn user_handler(Path(id): Path<u64>) -> Result<Json<serde_json::Value>, ApiError> {
    let name = get_user_from_db(id).await?;
    Ok(Json(json!({ "id": id, "name": name })))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(user_handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

This is a realistic starting point for an Axum API. The error model is fully explicit: the handler's signature tells you it can fail with ApiError, and ApiError tells you exactly what HTTP responses are possible. No magic, no hidden catches, and the compiler has verified everything.

Extractor Rejections: the 400 / 415 / 422 Split, and Customising Them

Not all errors come from your handler code. Extractors can reject a request before your handler ever runs, and each kind of failure has its own status code - with a plain-text body, not JSON, by default:

FailureStatusJsonRejection variant
Malformed JSON syntax (e.g. an unclosed brace)400 Bad RequestJsonSyntaxError
Valid JSON with the wrong shape (missing field, wrong type)422 Unprocessable EntityJsonDataError
Missing or wrong Content-Type (not application/json)415 Unsupported Media TypeMissingJsonContentType
The request body could not be read at all400 Bad RequestBytesRejection

The same split applies to other extractors: a Path segment that cannot be deserialised is a 400, and a Query string that cannot be deserialised is a 400.

If the default plain-text rejection is not what your API should return, do not look for a global extractor-error handler - there is not one. Instead, take the rejection into the handler in one of two ways:

use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::IntoResponse,
};
use serde_json::json;

// Option 1: receive the rejection as a Result and shape it yourself.
async fn create_user(
    payload: Result<Json<serde_json::Value>, JsonRejection>,
) -> impl IntoResponse {
    match payload {
        Ok(Json(value)) => (StatusCode::CREATED, Json(value)).into_response(),
        Err(JsonRejection::MissingJsonContentType(_)) => (
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            Json(json!({ "error": "expected Content-Type: application/json" })),
        )
            .into_response(),
        Err(JsonRejection::JsonSyntaxError(_)) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "malformed JSON" })),
        )
            .into_response(),
        Err(JsonRejection::JsonDataError(_)) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": "JSON does not match the expected shape" })),
        )
            .into_response(),
        Err(_) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "could not read request body" })),
        )
            .into_response(),
    }
}

JsonRejection is #[non_exhaustive], so a match on it needs a catch-all arm, as above. Option 2 is axum_extra::extract::WithRejection: wrap the extractor as WithRejection(Json(value), _): WithRejection<Json<T>, ApiError> and implement From<JsonRejection> for ApiError, so the rejection is converted into your own error type before the handler body runs. Both patterns give you per-extractor control; neither changes the default status codes, it only changes how they are presented.

What You Have Learned

Axum's predictable error model is built on a simple contract: handlers return Result, and both the success and error types implement IntoResponse. This means errors are converted into HTTP responses in one well‑defined place, and the Rust compiler enforces that every error type is convertible.

The decision framework for choosing between the approaches on this page is the size of the error surface you need to describe:

  • One endpoint, one failure. Return a bare StatusCode as the error. There is nothing to name and nothing to format.
  • A few endpoints, a few named failures. Define a small error enum and implement IntoResponse for it by hand. Each variant maps to one status and one body shape.
  • Many endpoints, many error kinds. Derive the enum with thiserror: the #[error("...")] strings give you Display for free, and #[from] wires up the ? conversions, so adding a new failure means adding one variant instead of one more manual impl.
  • Prototyping, before the error surface is settled. Reach for anyhow::Error behind a small IntoResponse wrapper that turns it into a 500 - but treat that as scaffolding, not the finished design, because it throws away the specific status and body your clients will eventually need.

The single most important insight is that the compiler, not a test suite, is what keeps this model honest: if a handler can fail in a way the client cannot understand, the code does not compile. That guarantee is what makes the model predictable, and it is why the error handling you write on day one still describes your API correctly a year later.