Handling Extractor Rejections with Result in Handlers

Learn how to catch and handle extractor failures manually by wrapping Axum extractors in Result types inside handler functions

When an extractor fails, Axum normally generates an error response and skips your handler entirely. You never see the failure inside your function. This page teaches you how to change that behavior by wrapping an extractor in Rust's Result type. The handler runs even when extraction fails, and you decide exactly what response the client receives.

The Default Rejection Behavior

Before using Result, you need a clear picture of what Axum does when an extractor fails. Imagine a handler that expects a JSON body through the Json extractor. If a client sends a request with malformed JSON, the Json extractor cannot parse the body. Axum detects this failure automatically and returns a default error response. The response contains an error message and a status code, but your handler code never executes. You had no chance to customize the response, log the failure, or try a different approach.

Here is a handler that relies on the default behavior. The code is short and works, but it offers no control:

// src/main.rs
use axum::{extract::Json, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(Json(payload): Json<CreateUser>) -> String {
    format!("Creating user {}", payload.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

When everything goes well, the client sends a valid JSON body like {"username": "alice", "email": "alice@example.com"} with the correct Content-Type: application/json header. The handler runs and returns a greeting. When the JSON is malformed, the handler silently never runs. Axum returns a default plain-text error response to the client (for example, Failed to parse the request body as JSON: ... with a text/plain content type). The server logs nothing unless you configured a logging layer. This is fine for simple APIs but weak for production systems where you want consistent error formats, detailed logging, or fallback behavior.

Why the Handler Is Skipped:

Axum processes extractors before it invokes your handler function. If any extractor in the parameter list fails, Axum converts that failure into an HTTP response and short-circuits the request. Your handler is never called because Axum already decided the response.

What a Rejection Type Is

Each extractor in Axum has an associated rejection type. A rejection type is an enum that describes every way that specific extractor can fail. For example, the Json extractor has a rejection type called JsonRejection. It has separate variants for a missing content type header, a syntax error in the JSON, a type mismatch during deserialization, and a failure to read the request body.

Think of a rejection type as a detailed error report. Instead of just saying "extraction failed," the rejection type tells you exactly what went wrong. The enum variants carry additional data. JsonRejection::JsonSyntaxError wraps a serde_path_to_error::Error<serde_json::Error> (Axum deserializes through serde_path_to_error, so the error carries the JSON path as well as the line and column where the parser got confused). JsonRejection::MissingJsonContentType tells you the client forgot to send the right header.

Every extractor exposes its rejection type through an associated type named Rejection. You do not need to remember the exact type name for each extractor in most cases, but you do need to import it when you wrap the extractor in Result.

The Core Pattern - Wrapping an Extractor in Result

The solution is to change the extractor from Json<CreateUser> to Result<Json<CreateUser>, JsonRejection>. This tells Axum: "Attempt the extraction, but do not short-circuit the request if it fails. Instead, give me the outcome as a Result."

Here is the smallest possible modification to the previous example:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(payload: Result<Json<CreateUser>, JsonRejection>) -> String {
    match payload {
        Ok(Json(user)) => format!("Creating user {}", user.username),
        Err(rejection) => format!("Failed to parse JSON: {:?}", rejection),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The signature changed in two places. The parameter type is now Result<Json<CreateUser>, JsonRejection>, and the import includes rejection::JsonRejection. Inside the handler, a simple match expression distinguishes the successful case from the failed case. The Ok arm destructures the Json wrapper to get the actual CreateUser struct. The Err arm has access to the full JsonRejection value.

The Handler Now Runs Every Time:

With the Result wrapper, your handler always executes regardless of whether extraction succeeded or failed. The extraction outcome becomes a value you receive and handle, just like any other function argument. This is the fundamental shift that gives you control.

Building the Result-Wrapped Handler Step by Step

Converting a regular handler to one that handles rejections is a sequential process. Each step depends on the previous one completing successfully.

1

Step 1: Identify the Extractor and Its Rejection Type

Look at the extractor you want to wrap. For Json<CreateUser>, the rejection type is JsonRejection. For Path<u32>, it is PathRejection. For Query<Pagination>, it is QueryRejection. Every extractor has exactly one rejection type. You can find it in the axum::extract::rejection module.

use axum::extract::rejection::JsonRejection;
2

Step 2: Wrap the Extractor Type in Result

Change the parameter type from Json<CreateUser> to Result<Json<CreateUser>, JsonRejection>. The Ok variant holds the successfully extracted value. The Err variant holds the rejection.

async fn create_user(payload: Result<Json<CreateUser>, JsonRejection>) -> String {
    // handler body goes here
}
3

Step 3: Match on the Result

Inside the handler, use a match expression to handle both cases. The Ok arm receives the extracted value wrapped in the original extractor type. The Err arm receives the rejection.

match payload {
    Ok(Json(user)) => { /* extraction succeeded */ }
    Err(rejection) => { /* extraction failed */ }
}
4

Step 4: Handle Each Rejection Variant

Refine the Err arm by matching on individual variants of the rejection type. This lets you return different responses for different failure modes.

Err(rejection) => match rejection {
    JsonRejection::MissingJsonContentType(_) => { /* no content type */ }
    JsonRejection::JsonSyntaxError(_) => { /* bad JSON */ }
    JsonRejection::JsonDataError(_) => { /* type mismatch */ }
    JsonRejection::BytesRejection(_) => { /* body read failed */ }
    _ => { /* unknown future variant */ }
}

Always Include the Catch-All Arm:

The _ arm in the inner match is not optional convenience. Axum may add new rejection variants in future minor versions. Without a catch-all, your code breaks when you upgrade Axum and a new variant appears. The _ arm future-proofs your handler. It also handles any nested rejection types that you have not explicitly enumerated.

Understanding JsonRejection in Depth

JsonRejection is the rejection type for the Json extractor. It deserves detailed coverage because Json is one of the most commonly used extractors and its rejection type has several distinct variants.

The variants of JsonRejection in the current version of Axum are:

  • MissingJsonContentType - The request did not include the Content-Type: application/json header, or the header value was not application/json. This is often the first mistake clients make when testing an API.
  • JsonSyntaxError - The request body contained JSON that is syntactically invalid. For example, missing a closing brace, using single quotes instead of double quotes, or leaving a trailing comma.
  • JsonDataError - The JSON was syntactically valid, but it did not match the target Rust type. For example, sending a string where a number is expected, or omitting a required field.
  • BytesRejection - Axum failed to read the request body. This usually indicates a network issue, a body that exceeded the configured size limit, or a client that disconnected mid-request.

Each variant carries additional data. JsonSyntaxError and JsonDataError wrap a serde_path_to_error::Error<serde_json::Error>, whose Display text already includes the line and column number (for example, age: expected value at line 1 column 26), so you can use it directly in error messages. BytesRejection wraps another rejection type that further describes the body-reading failure.

Let me show a handler that treats each variant differently and returns a meaningful HTTP status code and message:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(payload: Result<Json<CreateUser>, JsonRejection>) -> Response {
    match payload {
        Ok(Json(user)) => {
            let response_body = json!({
                "status": "success",
                "username": user.username,
                "message": "User created"
            });
            (StatusCode::CREATED, Json(response_body)).into_response()
        }
        Err(rejection) => match rejection {
            JsonRejection::MissingJsonContentType(_) => (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "error": "missing_content_type",
                    "message": "Content-Type header must be application/json"
                })),
            )
                .into_response(),
            JsonRejection::JsonSyntaxError(err) => (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "error": "syntax_error",
                    "message": format!("Invalid JSON: {}", err)
                })),
            )
                .into_response(),
            JsonRejection::JsonDataError(err) => (
                StatusCode::UNPROCESSABLE_ENTITY,
                Json(json!({
                    "error": "data_error",
                    "message": format!("JSON structure does not match expected type: {}", err)
                })),
            )
                .into_response(),
            JsonRejection::BytesRejection(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "body_read_failed",
                    "message": "Failed to read request body"
                })),
            )
                .into_response(),
            _ => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "unknown",
                    "message": "An unknown error occurred"
                })),
            )
                .into_response(),
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This is a complete, runnable program. The handler returns a Response directly so it can control every aspect of the HTTP response: status code, JSON body, and error details. A client that sends a missing field gets a 422 Unprocessable Entity response with a clear message. A client that sends malformed JSON gets a 400 Bad Request response with the line and column number where the parser failed. A client that sends the wrong content type gets a 400 Bad Request response telling them exactly what to fix.

The Error Type Must Match the Extractor:

A common mistake is importing the wrong rejection type. Wrapping Json<CreateUser> in Result requires the error type to be exactly JsonRejection, not PathRejection or QueryRejection or any other type. If the types do not match, Rust will produce a compile error. The error message may look confusing because it points to a trait bound failure deep inside Axum. The fix is always to check the import and ensure the rejection type corresponds to the extractor.

Using the Question Mark Operator for Cleaner Code

Rust's ? operator works inside functions that return a Result. If you design your handler to return a Result<T, E> where E is the same rejection type as the wrapped extractor, you can use ? to propagate the rejection out of the handler early.

Here is the pattern:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
}
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) -> Result<Json<Value>, JsonRejection> {
    let Json(user) = payload?;
    Ok(Json(json!({
        "status": "success",
        "username": user.username,
        "message": "User created"
    })))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The handler's return type is now Result<Json<Value>, JsonRejection>. The ? operator on payload does the following: if payload is Ok(Json(user)), the inner Json<CreateUser> is destructured and user is bound to the CreateUser struct. If payload is Err(rejection), the rejection is immediately returned from the handler as Err(rejection). Axum then converts that Err(JsonRejection) into an HTTP response using the rejection's built-in IntoResponse implementation.

This is useful when you want the default rejection behavior for the error case but still want to run some code on success. The handler is concise, and the rejection automatically converts to a reasonable error response without you writing any error-handling code.

How Axum Converts Rejections to Responses:

Every rejection type in Axum implements the IntoResponse trait. This means a rejection can be converted into an HTTP response with a single call. When your handler returns Err(rejection), Axum calls into_response() on it and sends the resulting response to the client. This is the same conversion that happens automatically when an extractor fails without a Result wrapper.

Path Extractor with Result

The Path extractor fails when a path parameter cannot be deserialized into the target type. For example, if the route template expects {user_id} and the client navigates to /users/abc, extracting Path<u32> fails because "abc" is not a valid unsigned 32-bit integer.

The rejection type for Path is PathRejection. It has variants for failed deserialization and missing path parameters:

// src/main.rs
use axum::{
    extract::{rejection::PathRejection, Path},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use serde_json::json;
use axum::Json;
async fn get_user(
    user_id: Result<Path<u32>, PathRejection>,
) -> Response {
    match user_id {
        Ok(Path(id)) => {
            let body = json!({
                "status": "success",
                "user_id": id,
                "message": "User found"
            });
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(rejection) => match rejection {
            PathRejection::FailedToDeserializePathParams(err) => {
                let body = json!({
                    "error": "invalid_path_parameter",
                    "message": format!("Path parameter must be a number: {}", err)
                });
                (StatusCode::BAD_REQUEST, Json(body)).into_response()
            }
            PathRejection::MissingPathParams(_) => {
                let body = json!({
                    "error": "missing_path_params",
                    "message": "Path parameters were not available"
                });
                (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
            }
            _ => {
                let body = json!({
                    "error": "unknown",
                    "message": "An unknown path error occurred"
                });
                (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
            }
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

When a client navigates to /users/42, the handler receives Ok(Path(42)) and returns a success response with the user ID. When a client navigates to /users/abc, the Path extractor fails, and the handler receives Err(PathRejection::FailedToDeserializePathParams(err)). It returns a 400 Bad Request response explaining that the path parameter must be a number.

PathRejection Variant Naming:

The variant FailedToDeserializePathParams is verbose but descriptive. It means Axum could not convert the raw string from the URL into the target type. This happens when you use Path<u32> and the URL segment is not a valid number. The MissingPathParams variant is rare in typical applications because Axum automatically populates path parameters when routing a request. It mainly appears when Path is extracted outside of routing, for example in middleware or from a manually constructed request that never went through the router (a handler that takes Request before Path would not compile at all, since body-consuming extractors must be last).

Query Extractor with Result

The Query extractor fails when the query string cannot be deserialized into the target struct. This commonly happens when a query parameter has the wrong type. For example, if the target struct expects page to be a u32 and the URL contains ?page=abc, extraction fails.

The rejection type is QueryRejection, and its primary variant is FailedToDeserializeQueryString:

// src/main.rs
use axum::{
    extract::{rejection::QueryRejection, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use serde::Deserialize;
use serde_json::json;
use axum::Json;
#[derive(Deserialize)]
struct Pagination {
    page: u32,
    limit: u32,
}
async fn list_users(
    query: Result<Query<Pagination>, QueryRejection>,
) -> Response {
    match query {
        Ok(Query(params)) => {
            let body = json!({
                "status": "success",
                "page": params.page,
                "limit": params.limit,
                "message": "Users retrieved"
            });
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(rejection) => match rejection {
            QueryRejection::FailedToDeserializeQueryString(err) => {
                let body = json!({
                    "error": "invalid_query_string",
                    "message": format!("Query string does not match expected format: {}", err)
                });
                (StatusCode::BAD_REQUEST, Json(body)).into_response()
            }
            _ => {
                let body = json!({
                    "error": "unknown",
                    "message": "An unknown query error occurred"
                });
                (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
            }
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", get(list_users));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

A client that navigates to /users?page=1&limit=20 gets a success response. A client that navigates to /users?page=abc&limit=20 gets a 400 Bad Request response with a message explaining the query string could not be deserialized.

String and Bytes Body Extractors with Result

The String and Bytes extractors read the raw request body without parsing it as JSON. They can fail when the body cannot be buffered. The String extractor has an additional failure mode: the body might not be valid UTF-8 text.

The rejection type for String is StringRejection. It has an InvalidUtf8 variant that triggers when the body contains invalid UTF-8 bytes. The rejection type for Bytes is BytesRejection, which has a FailedToBufferBody variant.

Here is a handler that wraps the String extractor in Result:

// src/main.rs
use axum::{
    extract::rejection::StringRejection,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde_json::json;
use axum::Json;
async fn upload_text(body: Result<String, StringRejection>) -> Response {
    match body {
        Ok(text) => {
            let body = json!({
                "status": "success",
                "characters": text.len(),
                "content": text
            });
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(rejection) => match rejection {
            StringRejection::InvalidUtf8(_) => {
                let body = json!({
                    "error": "invalid_utf8",
                    "message": "Request body is not valid UTF-8 text"
                });
                (StatusCode::BAD_REQUEST, Json(body)).into_response()
            }
            _ => {
                let body = json!({
                    "error": "body_read_failed",
                    "message": "Failed to read request body"
                });
                (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
            }
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload-text", post(upload_text));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This handler accepts any request body and returns it along with its character count. When the body is valid UTF-8, the response echoes the text. When the body contains invalid UTF-8 bytes, the handler returns a 400 Bad Request response with a clear error message.

The Bytes extractor works similarly but accepts any binary data. Here is the equivalent example:

// src/main.rs
use axum::{
    body::Bytes,
    extract::rejection::BytesRejection,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde_json::json;
use axum::Json;
async fn upload_bytes(body: Result<Bytes, BytesRejection>) -> Response {
    match body {
        Ok(bytes) => {
            let body = json!({
                "status": "success",
                "bytes_received": bytes.len()
            });
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(rejection) => {
            let body = json!({
                "error": "body_read_failed",
                "message": format!("Failed to read request body: {:?}", rejection)
            });
            (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload-bytes", post(upload_bytes));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This handler reports how many bytes were received. It does not care what the bytes represent. The Err case is rare for local connections but can occur if the body exceeds the configured size limit or the client disconnects mid-upload.

Body Extractors Must Be Last:

Both String and Bytes consume the request body. This means they must be the last extractor in the handler's parameter list. If you wrap them in Result, the same rule applies. Attempting to place a body-consuming extractor before another extractor causes a compile error because Axum enforces the rule at the type level.

Extension Extractor with Result

The Extension extractor retrieves data that was inserted into the request context by a middleware layer or the application state. It fails when the requested extension type has not been registered. This is a configuration problem, not a client input problem.

The rejection type is ExtensionRejection, and its main variant is MissingExtension:

// src/main.rs
use axum::{
    extract::{rejection::ExtensionRejection, Extension},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use serde_json::json;
use axum::Json;
#[derive(Clone)]
struct AppConfig {
    app_name: String,
}
async fn config_handler(
    ext: Result<Extension<AppConfig>, ExtensionRejection>,
) -> Response {
    match ext {
        Ok(Extension(config)) => {
            let body = json!({
                "status": "success",
                "app_name": config.app_name
            });
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(_) => {
            let body = json!({
                "error": "configuration_missing",
                "message": "Application configuration was not registered"
            });
            (StatusCode::INTERNAL_SERVER_ERROR, Json(body)).into_response()
        }
    }
}
#[tokio::main]
async fn main() {
    let config = AppConfig {
        app_name: "My Axum App".to_string(),
    };
    let app = Router::new()
        .route("/config", get(config_handler))
        .layer(Extension(config));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The layer(Extension(config)) call registers the AppConfig type in the request context. Every handler that extracts Extension<AppConfig> will find it. If you remove the .layer() call, the extension is missing, and the handler receives Err(ExtensionRejection::MissingExtension). The handler then returns a 500 Internal Server Error response indicating a server-side configuration problem.

Missing Extension Indicates a Server Bug:

Unlike JSON or query parameter failures, a missing extension is almost always a configuration error in your application, not a client error. You should return a 500-level status code, not a 400-level code. A 400 Bad Request tells the client they did something wrong. A 500 Internal Server Error tells the client that the server has a problem. Missing extensions are the server's fault.

Returning a Rejection Directly with the Question Mark Operator

Sometimes you want to handle the success case and simply let the rejection flow through as the default error response. This is especially useful when you have several extractors and only want to customize the handling for one of them.

Here is an example with two extractors where one is wrapped in Result and the other is not:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Path, Query, Json},
    http::StatusCode,
    routing::get,
    Router,
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct Pagination {
    page: u32,
    limit: u32,
}
async fn list_user_notes(
    Path(user_id): Path<u32>,
    Query(pagination): Query<Pagination>,
    notes_filter: Result<Json<NoteFilter>, JsonRejection>,
) -> Result<Json<serde_json::Value>, JsonRejection> {
    let Json(filter) = notes_filter?;
    Ok(Json(json!({
        "user_id": user_id,
        "page": pagination.page,
        "limit": pagination.limit,
        "filter": filter.keyword
    })))
}
#[derive(Deserialize)]
struct NoteFilter {
    keyword: String,
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}/notes", get(list_user_notes));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

In this handler, Path<u32> and Query<Pagination> are regular extractors. If either fails, Axum returns the default error response and the handler never runs. The Json<NoteFilter> extractor is wrapped in Result. If JSON extraction fails, the handler runs and the ? operator propagates the rejection as the handler's return value. Axum converts it to an HTTP response. If JSON extraction succeeds, the handler returns the combined data from all three extractors.

This pattern is powerful because it lets you selectively handle failures. You let Axum handle the common cases automatically while taking manual control of the specific extractor that needs custom treatment.

Handler Return Type Compatibility:

For the ? operator to work, the handler's return type must be a Result whose error type matches the rejection type of the wrapped extractor. Here, the handler returns Result<Json<Value>, JsonRejection>, and the wrapped extractor is Result<Json<NoteFilter>, JsonRejection>. Both share the same error type JsonRejection, so the ? operator can propagate the rejection naturally. If the types mismatch, Rust will not compile.

Customizing the Entire Response for a Handler

One of the most powerful uses of Result-wrapped extractors is customizing the complete error response for a specific handler. Instead of returning the default rejection, you can convert it into a fully custom response with your own status code, headers, and body.

Here is a comprehensive example that converts JsonRejection into a custom JSON error response with a consistent format:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct CreateUser {
    username: String,
    email: String,
    age: u32,
}
async fn create_user(
    result: Result<Json<CreateUser>, JsonRejection>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    match result {
        Ok(Json(payload)) => Ok(Json(json!({
            "status": "success",
            "username": payload.username,
            "email": payload.email,
            "age": payload.age
        }))),
        Err(rejection) => match rejection {
            JsonRejection::JsonDataError(err) => {
                Err((StatusCode::UNPROCESSABLE_ENTITY, format!(
                    "The JSON structure does not match the expected user schema: {}",
                    err
                )))
            }
            JsonRejection::JsonSyntaxError(err) => {
                Err((StatusCode::BAD_REQUEST, format!(
                    "The request body contains invalid JSON: {}",
                    err
                )))
            }
            JsonRejection::MissingJsonContentType(_) => {
                Err((StatusCode::BAD_REQUEST,
                    "Missing `Content-Type: application/json` header".to_string()))
            }
            JsonRejection::BytesRejection(_) => {
                Err((StatusCode::INTERNAL_SERVER_ERROR,
                    "Failed to buffer request body".to_string()))
            }
            _ => {
                Err((StatusCode::INTERNAL_SERVER_ERROR,
                    "Unknown error".to_string()))
            }
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The handler's return type is Result<Json<Value>, (StatusCode, String)>. The success case returns Ok(Json(...)), which Axum converts into a 200 OK response with the JSON body. The error case returns Err((StatusCode, String)), where the tuple contains the HTTP status code and a plain-text error message. The tuple (StatusCode, String) implements IntoResponse, so Axum can convert it directly.

Every rejection variant produces a different response. A missing content type yields a 400 Bad Request with a clear message. A JSON syntax error yields a 400 Bad Request with line and column information. A data type mismatch yields a 422 Unprocessable Entity with a schema mismatch message. A body-read failure yields a 500 Internal Server Error.

Consistent Error Format Achieved:

This handler produces consistent, predictable error responses for every failure mode. Clients can rely on receiving a clear plain-text error message with an appropriate HTTP status code. This is significantly better than the default Axum rejection response, which may have a generic format that does not match your API's conventions.

Handling Multiple Result-Wrapped Extractors in One Handler

You can wrap more than one extractor in Result within the same handler. Each Result has its own error type, and you match on them independently. This is useful when different extractors require different failure handling logic.

Here is an example with both Path and Query wrapped in Result:

// src/main.rs
use axum::{
    extract::{rejection::PathRejection, rejection::QueryRejection, Path, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use serde::Deserialize;
use serde_json::json;
use axum::Json;
#[derive(Deserialize)]
struct SearchParams {
    keyword: String,
    limit: u32,
}
async fn search_users(
    user_id: Result<Path<u32>, PathRejection>,
    query: Result<Query<SearchParams>, QueryRejection>,
) -> Response {
    let Ok(Path(id)) = user_id else {
        let body = json!({
            "error": "invalid_user_id",
            "message": "User ID must be a valid number"
        });
        return (StatusCode::BAD_REQUEST, Json(body)).into_response();
    };
    let Ok(Query(params)) = query else {
        let body = json!({
            "error": "invalid_query",
            "message": "Query string must include keyword and limit"
        });
        return (StatusCode::BAD_REQUEST, Json(body)).into_response();
    };
    let body = json!({
        "status": "success",
        "user_id": id,
        "keyword": params.keyword,
        "limit": params.limit
    });
    (StatusCode::OK, Json(body)).into_response()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{user_id}/search", get(search_users));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This handler uses Rust's let-else syntax, which is clean and readable. The let Ok(Path(id)) = user_id else pattern extracts the inner value if the result is Ok, and jumps to the else block if it is Err. The else block returns early with a custom error response. The same pattern applies to the query parameters.

The benefit of this approach is clarity. Each extractor has its own error handling block, and the main logic only runs when both extractions succeed. The downside is verbosity when you have many extractors, but that trade-off is often worth it for explicit control.

When to Use Result-Wrapped Extractors vs. Custom Extractors

Two techniques exist for customizing extractor error responses: wrapping the extractor in Result inside the handler, or creating a completely custom extractor type. Both achieve the same goal, but they are appropriate in different situations.

Use Result-wrapped extractors when:

  • You only need custom error handling for a single handler or a few handlers
  • The extractor you are wrapping is already built into Axum
  • You want to keep the extraction logic unchanged and only customize the error response
  • The error handling is simple enough to write inline in the handler

Create a custom extractor when:

  • You need to reuse the same error handling across many handlers
  • You want to extract data in a way that Axum's built-in extractors do not support
  • You want to combine multiple extraction steps into a single extractor
  • You want the custom behavior to be the default for your entire application

For most applications, Result-wrapped extractors are sufficient. They require much less code than custom extractors and are easier to understand. A custom extractor is justified when you find yourself copying the same match expression into several handlers.

Keep It Simple First:

Beginners should prefer Result-wrapped extractors over custom extractors. The Result approach is self-contained, easy to debug, and does not require understanding the FromRequest trait. Only move to custom extractors when the repetition becomes painful.

Common Mistakes and Misconceptions

Several errors trip up beginners when they start using Result-wrapped extractors. Being aware of them before they happen saves significant debugging time.

Mismatched Rejection Type:

The error type in the Result must exactly match the rejection type of the extractor. Using Result<Json<Value>, PathRejection> when the extractor is Json produces a compile error. Rust's error messages may point to a trait bound failure in Axum's internals, making the root cause hard to find. Always double-check the import and the type name.

Omitting the Catch-All Arm:

Matching on rejection variants without a _ arm is risky. Axum may add new variants in future releases. Your code will fail to compile when you upgrade Axum and the new variant is not covered. Always include _ as the final arm.

Forgetting to Import the Rejection Type:

The rejection types live in the axum::extract::rejection module. They are not re-exported at the top level of axum::extract. You need to write use axum::extract::rejection::JsonRejection; or use the full path. Omitting the import is one of the most common compile errors.

Confusing Ok and Err Arms:

The Ok arm of the Result still contains the extractor wrapper. Ok(Json(user)) destructures the Json wrapper to get the CreateUser struct. If you write Ok(payload) and then try to access payload.username, you will get a compile error because payload is of type Json<CreateUser>, not CreateUser. You must destructure the wrapper.

Body Extractor Not Last:

Even when wrapped in Result, body-consuming extractors like String, Bytes, and Json must still be the last parameter in the handler. Axum enforces this rule at the type level. Placing a body extractor before another extractor causes a compile error. The Result wrapper does not exempt you from this rule.

Practical Example - A Complete JSON Validation Handler

To bring everything together, here is a complete, realistic handler that validates user input through the Json extractor, handles every rejection variant explicitly, and returns structured JSON responses. This is the kind of code you would write in a production API:

// src/main.rs
use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct CreateUserRequest {
    username: String,
    email: String,
    age: u8,
}
async fn create_user(
    payload: Result<Json<CreateUserRequest>, JsonRejection>,
) -> Response {
    match payload {
        Ok(Json(user)) => {
            if user.username.trim().is_empty() {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": "invalid_username",
                        "message": "Username must not be empty"
                    })),
                )
                    .into_response();
            }
            if user.age < 18 {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": "underage",
                        "message": "User must be at least 18 years old"
                    })),
                )
                    .into_response();
            }
            (
                StatusCode::CREATED,
                Json(json!({
                    "status": "success",
                    "user_id": 12345,
                    "username": user.username,
                    "email": user.email,
                    "age": user.age
                })),
            )
                .into_response()
        }
        Err(rejection) => match rejection {
            JsonRejection::MissingJsonContentType(_) => (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "error": "missing_content_type",
                    "message": "The request must include `Content-Type: application/json`"
                })),
            )
                .into_response(),
            JsonRejection::JsonSyntaxError(err) => (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "error": "invalid_json_syntax",
                    "message": format!("JSON is malformed: {}", err)
                })),
            )
                .into_response(),
            JsonRejection::JsonDataError(err) => (
                StatusCode::UNPROCESSABLE_ENTITY,
                Json(json!({
                    "error": "invalid_json_structure",
                    "message": "JSON does not match the expected user schema",
                    "details": err.to_string()
                })),
            )
                .into_response(),
            JsonRejection::BytesRejection(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "body_read_failed",
                    "message": "Failed to read the request body"
                })),
            )
                .into_response(),
            _ => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "unknown",
                    "message": "An unknown error occurred"
                })),
            )
                .into_response(),
        },
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This handler combines extraction-time rejection handling with application-level validation. After the JSON is successfully extracted, the code checks whether the username is non-empty and whether the user is at least 18 years old. If those business rules fail, the handler returns a custom error response. If the JSON itself fails to parse, the rejection handling path takes over.

Test this handler with a few scenarios:

  1. Send a valid request with {"username": "alice", "email": "alice@example.com", "age": 30} and the correct content type. You get a 201 Created response with a success message.
  2. Send the same request without the Content-Type header. You get a 400 Bad Request with a "missing_content_type" error.
  3. Send malformed JSON like {"username": "alice",}. You get a 400 Bad Request with an "invalid_json_syntax" error and the exact line and column.
  4. Send valid JSON that omits the age field. You get a 422 Unprocessable Entity with an "invalid_json_structure" error.
  5. Send {"username": "", "email": "alice@example.com", "age": 30}. You get a 400 Bad Request with an "invalid_username" error because the application-level validation catches it.

Complete Error Control Achieved:

This handler gives you complete control over every error scenario. The client receives consistent, structured JSON error responses with appropriate status codes. The server logs are clean because every failure path is handled explicitly. This is the pattern to follow for production-grade APIs.

Summary

The Result-wrapped extractor pattern is the bridge between Axum's automatic rejection handling and full manual control. When an extractor fails by default, Axum returns a generic error response and your handler never runs. By wrapping an extractor in Result<T, T::Rejection>, you change the flow: the handler always runs, and the extraction outcome becomes a value you process like any other argument.

The most important insight from this page is that rejection types are enums that describe every failure mode of an extractor. JsonRejection tells you whether the content type header was missing, the JSON syntax was wrong, the data structure did not match, or the body could not be read. PathRejection tells you whether a path parameter failed to deserialize. QueryRejection tells you whether the query string failed to deserialize. Each variant carries additional data you can use in error messages.

The decision framework is simple. If you need custom error handling in one or two handlers, wrap the extractor in Result and match on the rejection inside the handler. If you need the same custom behavior in many handlers, create a custom extractor. For most beginners, the Result approach is sufficient and much easier to understand.

The habit to take away is to decide, for each extractor in a handler, who owns its failure: Axum's default response, your match on the rejection, or the ? operator passing it through. Making that choice deliberately is what turns rejection handling from a compile-time chore into the shape of your API's error contract.