WithRejection wrapper

Learn how to use the WithRejection wrapper from axum-extra to customize the error responses returned when an extractor rejects a request.

When an Axum extractor fails - for example, when a query parameter is missing or a JSON body is malformed - the framework returns a default error response. Usually that is a plain text message with a specific HTTP status code like 400 Bad Request or 422 Unprocessable Entity. The default is fine while you're building an API, but as soon as you want to control exactly what your clients see - maybe return a JSON error object with your own structure, or add extra headers, or use a different status code - you need a way to intercept the rejection and transform it into your own response.

That is exactly what the WithRejection wrapper from the axum-extra crate does. It wraps any extractor, catches the rejection it produces, and lets you run a function that turns that rejection into a custom HTTP response. You get to keep using all of Axum's built-in extractors (Query, Json, Path, custom ones, and so on), but you decide what goes back to the client when something goes wrong.

This page assumes you have already worked with Axum extractors and have seen what a "rejection" is - the internal error type that extractors return when they cannot produce a value. If the word "rejection" still feels new, think of it as the extractor saying "I can't give you the data you asked for because the request didn't contain what I needed." A rejection is normally converted by Axum's default machinery into an HTTP response, but WithRejection lets you step in and do that conversion yourself.

Why the default rejection responses are often not enough

Axum has a built-in way to turn a rejection into an HTTP response. For example, if you write a handler that expects Query<SomeStruct> and the request does not include the required query parameters, Axum will produce a 400 Bad Request with a body like Failed to deserialize query string: missing field \page``. That is helpful during development but rarely what you want in production.

Imagine you are building a public JSON API. Your clients expect every error response to look like this:

{
  "error": {
    "code": "invalid_query",
    "message": "The 'page' query parameter is required."
  }
}

With default rejections, you'd get a plain text body and no consistent JSON structure. You could handle this manually inside each handler by using Result and building the response yourself, but that becomes repetitive and error‑prone. WithRejection gives you a clean, reusable way to apply your custom error format to any extractor without writing boilerplate in every handler.

Where WithRejection lives:

WithRejection is not part of Axum's core crate. It comes from axum-extra, a separate crate maintained by the Axum team. You need to add axum-extra to your Cargo.toml to use it.

Adding axum-extra to your project

Before you can use WithRejection, make sure axum-extra is in your dependencies. Open your Cargo.toml and add:

[dependencies]
axum = "0.8"
axum-extra = { version = "0.12", features = ["with-rejection"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

The exact versions may differ depending on when you're reading this. The important part is that axum-extra is included with the with-rejection feature enabled: WithRejection is feature-gated, and without that feature the type does not exist in the crate at all.

A first look at WithRejection

The simplest way to understand WithRejection is to see it in action. Suppose you have a handler that extracts a query parameter page as a u32, using a struct:

use axum::extract::Query;
use axum::response::IntoResponse;
use serde::Deserialize;
#[derive(Deserialize)]
struct PageParams {
    page: u32,
}
async fn list_items(Query(params): Query<PageParams>) -> impl IntoResponse {
    // ...
}

If the request does not include ?page=..., or if page is not a valid u32, Axum will reject the extraction and return its default error. To replace that default error with your own response, wrap the Query extractor inside WithRejection and name a response type that knows how to build itself from the rejection:

use axum::extract::{rejection::QueryRejection, Query};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
#[derive(Deserialize)]
struct PageParams {
    page: u32,
}
struct QueryError(Response);
impl From<QueryRejection> for QueryError {
    fn from(rejection: QueryRejection) -> Self {
        QueryError(
            (
                axum::http::StatusCode::BAD_REQUEST,
                format!("Query error: {rejection}"),
            )
                .into_response(),
        )
    }
}
impl IntoResponse for QueryError {
    fn into_response(self) -> Response {
        self.0
    }
}
async fn list_items(
    WithRejection(Query(params), _): WithRejection<Query<PageParams>, QueryError>,
) -> Response {
    // If we get here, extraction succeeded and `params.page` is available.
    format!("You asked for page {}", params.page).into_response()
}

WithRejection has two generic parameters: the extractor type (Query<PageParams>) and a response type (QueryError). The response type must implement two traits: From<QueryRejection>, so Axum can build it from the rejection, and IntoResponse, so Axum can turn it into an HTTP response. The second element of the tuple is a PhantomData<QueryError>, which carries no value, so you bind it as _ in the handler. You never pass a function: the mapping from rejection to response lives in the From impl, not in a value you supply.

Understanding the signature:

The exact signature of WithRejection can be tricky at first. It is a tuple struct WithRejection<E, R>(pub E, pub PhantomData<R>). The second generic R is a type, not a function: it must implement From<E::Rejection> and IntoResponse. In the handler you write WithRejection(Extractor, _) and name R in the type annotation; Axum constructs the PhantomData itself during extraction.

To avoid confusion, let's build a full, compile-ready example and run it.

Complete basic example: custom query error response

We'll create a small Axum application with one route that expects a page query parameter. If the parameter is missing or invalid, we want to return a JSON object like {"error":"invalid_page"} with status 422 Unprocessable Entity. Otherwise, we return a success message.

Create a new Rust project and add the dependencies as shown earlier. Then write the following in src/main.rs:

use axum::{
    extract::{rejection::QueryRejection, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct PageParams {
    page: u32,
}
struct QueryError(Response);
impl From<QueryRejection> for QueryError {
    fn from(rejection: QueryRejection) -> Self {
        let body = json!({
            "error": "invalid_page",
            "detail": rejection.to_string(),
        });
        QueryError((StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response())
    }
}
impl IntoResponse for QueryError {
    fn into_response(self) -> Response {
        self.0
    }
}
async fn list_items(
    WithRejection(Query(params), _): WithRejection<Query<PageParams>, QueryError>,
) -> Response {
    format!("Page requested: {}", params.page).into_response()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", get(list_items));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run the server and open your browser or use curl:

  • Visiting http://127.0.0.1:3000/items?page=5 returns Page requested: 5.
  • Visiting http://127.0.0.1:3000/items (missing page) returns a JSON body with status 422 and the custom error structure.
  • Visiting http://127.0.0.1:3000/items?page=abc also triggers the custom error because abc cannot be parsed as u32.

This is the core idea: your handler code stays clean, and the error mapping is separated into a small reusable response type.

How WithRejection actually works under the hood

When Axum processes a request, it calls the FromRequest implementation for each extractor in the handler's argument list. For a normal extractor like Query<T>, that implementation returns either Ok(T) or Err(SomeRejection). The rejection is then passed to Axum's default rejection handler, which converts it into an HTTP response and aborts the request.

WithRejection<E, R> changes that flow. Its FromRequest implementation still calls the inner extractor E. If the inner extractor succeeds, WithRejection returns Ok(WithRejection(value, PhantomData)) and the handler runs normally. If the inner extractor fails with a rejection, WithRejection does not return that rejection to Axum's default handler. Instead, it converts the rejection into R with R::from(rejection) and returns Err(R). Axum then turns R into a response using its IntoResponse impl and sends that to the client, bypassing the default rejection handling. No function is called anywhere in this flow: the conversion is a From impl on the response type.

This means the rejection never reaches Axum's default error machinery. You have complete control over what the client sees.

A helpful mental model: WithRejection is like a safety net around an extractor. The extractor throws a ball (the rejection) into the net, and the net is a response type you wrote whose From impl turns the ball into a finished, polished response.

Why this is a good design:

Because WithRejection is itself an extractor, you can use it anywhere you would use any other extractor: in a handler argument, nested inside other wrappers, or even behind other extractors. It composes with the rest of Axum's ecosystem.

Using WithRejection with custom extractors

The previous example used a built-in extractor (Query). In real applications, you often build custom extractors that do things like check an API key, verify a JWT, or load a user from a database. Those custom extractors also produce rejections, and you might want to map those rejections to specific HTTP responses.

Let's design a small custom extractor that checks for a header X-API-Key and rejects the request if the header is missing or if the key is incorrect. We will then use WithRejection to return a 401 Unauthorized response with a JSON body whenever the key is invalid.

First, define the custom extractor and its rejection type:

use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
use serde_json::json;
#[derive(Debug)]
struct ApiKey(String);
#[derive(Debug)]
enum ApiKeyRejection {
    MissingHeader,
    InvalidKey,
}
impl IntoResponse for ApiKeyRejection {
    fn into_response(self) -> Response {
        // Default response if we didn't use WithRejection; for completeness.
        let (status, message) = match self {
            ApiKeyRejection::MissingHeader => (StatusCode::BAD_REQUEST, "Missing X-API-Key"),
            ApiKeyRejection::InvalidKey => (StatusCode::UNAUTHORIZED, "Invalid API key"),
        };
        (status, message).into_response()
    }
}
impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = ApiKeyRejection;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let key = parts
            .headers
            .get("x-api-key")
            .ok_or(ApiKeyRejection::MissingHeader)?
            .to_str()
            .map_err(|_| ApiKeyRejection::InvalidKey)?;
        if key == "secret123" {
            Ok(ApiKey(key.to_string()))
        } else {
            Err(ApiKeyRejection::InvalidKey)
        }
    }
}

Now, in a handler, we want to use ApiKey but map its rejection to a custom JSON response with status 401 and a specific error code. We define a response type that builds itself from the rejection:

struct ApiKeyError(Response);
impl From<ApiKeyRejection> for ApiKeyError {
    fn from(rejection: ApiKeyRejection) -> Self {
        let (status, code) = match rejection {
            ApiKeyRejection::MissingHeader => (StatusCode::BAD_REQUEST, "missing_api_key"),
            ApiKeyRejection::InvalidKey => (StatusCode::UNAUTHORIZED, "invalid_api_key"),
        };
        let body = json!({ "error": code });
        ApiKeyError((status, axum::Json(body)).into_response())
    }
}
impl IntoResponse for ApiKeyError {
    fn into_response(self) -> Response {
        self.0
    }
}

Then the handler signature looks like:

async fn protected_route(
    WithRejection(api_key, _): WithRejection<ApiKey, ApiKeyError>,
) -> Response {
    format!("Hello, user with key {}", api_key.0).into_response()
}

Don't forget to add the route:

let app = Router::new()
    .route("/items", get(list_items))
    .route("/protected", get(protected_route));

Now, requests to /protected without the X-API-Key header get a 400 JSON error, and with an incorrect key get a 401 JSON error. The handler never runs unless the key is correct. This separation keeps your business logic clean and your error formatting consistent.

Mapping rejection to different response types

The response type you provide to WithRejection must implement IntoResponse, and its From impl decides what the client sees. That gives you enormous flexibility: you can return plain text, HTML, JSON, a full Response with custom headers, or even a streaming body. The choice depends on the API you are building.

Here is an example that returns plain text for a missing page parameter, but returns HTML if the rejection is of a different variant. We match on the rejection variants inside the From impl:

use axum::{
    extract::{rejection::QueryRejection, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
#[derive(Deserialize)]
struct PageParams {
    page: u32,
}
struct QueryErrorAdvanced(Response);
impl From<QueryRejection> for QueryErrorAdvanced {
    fn from(rejection: QueryRejection) -> Self {
        let response = match rejection {
            QueryRejection::FailedToDeserializeQueryString(err) => {
                // This variant occurs when the query string cannot be deserialized into the target type.
                (StatusCode::BAD_REQUEST, format!("Bad query: {err}")).into_response()
            }
            _ => {
                // For any other query rejection, return an HTML page.
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    axum::response::Html("<h1>Unexpected query error</h1>".to_string()),
                )
                    .into_response()
            }
        };
        QueryErrorAdvanced(response)
    }
}
impl IntoResponse for QueryErrorAdvanced {
    fn into_response(self) -> Response {
        self.0
    }
}
async fn list_items(
    WithRejection(Query(params), _): WithRejection<Query<PageParams>, QueryErrorAdvanced>,
) -> Response {
    format!("Page requested: {}", params.page).into_response()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", get(list_items));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Note that QueryRejection is an enum with several variants. You can match on them to provide different responses for different failure reasons. This is much more precise than catching everything as one generic error.

Learning the rejection enum:

Each built-in extractor has its own rejection type. Query<T> produces QueryRejection, Json<T> produces JsonRejection, Path<T> produces PathRejection, and so on. To use WithRejection effectively, you should explore the variants of these rejection types in the Axum documentation. They tell you exactly why the extraction failed, which helps you decide the right status code and error message.

Can you pass a closure instead of a type?

No, because there is nothing to pass a closure to. WithRejection does not take a mapping function as a value: its second generic is a response type, and the conversion lives in that type's From impl. The second field of the tuple struct is a PhantomData, which is why you bind it as _ in the handler. If your mapping logic is short and used only once, define the small response type next to the handler; named functions are not involved at all, so there is no closure question to answer.

Composing WithRejection with other extractors

You are not limited to a single WithRejection in a handler. You can wrap multiple extractors, each with its own rejection mapping. Axum will try each extractor in order, and the first one that rejects will immediately produce its mapped response, skipping the rest.

Consider a handler that needs both a valid Query<PageParams> and a valid Json<RequestPayload>:

use axum::{
    extract::{rejection::{JsonRejection, QueryRejection}, Json, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
#[derive(Deserialize)]
struct PageParams {
    page: u32,
    per_page: u32,
}
#[derive(Deserialize)]
struct CreateItemPayload {
    name: String,
    price: f64,
}
struct JsonError(Response);
impl From<JsonRejection> for JsonError {
    fn from(rejection: JsonRejection) -> Self {
        JsonError((StatusCode::BAD_REQUEST, format!("JSON error: {rejection}")).into_response())
    }
}
impl IntoResponse for JsonError {
    fn into_response(self) -> Response {
        self.0
    }
}
struct QueryError(Response);
impl From<QueryRejection> for QueryError {
    fn from(rejection: QueryRejection) -> Self {
        QueryError((StatusCode::UNPROCESSABLE_ENTITY, format!("Query error: {rejection}")).into_response())
    }
}
impl IntoResponse for QueryError {
    fn into_response(self) -> Response {
        self.0
    }
}
async fn create_item(
    WithRejection(Query(params), _): WithRejection<Query<PageParams>, QueryError>,
    WithRejection(Json(payload), _): WithRejection<Json<CreateItemPayload>, JsonError>,
) -> Response {
    format!(
        "Creating item '{}' (page {}, per_page {})",
        payload.name, params.page, params.per_page
    )
    .into_response()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", post(create_item));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The order matters: if the query is missing, the query rejection mapping runs first and the JSON extractor is never attempted. That's usually what you want, because you get a clear, specific error for each part of the request.

Handling rejection mapping for extractors that may not reject

Sometimes you have an extractor that never rejects, like Extension<T> if you have added the extension to the router, or HeaderMap which always succeeds. WithRejection still works, but the From impl will never run, because the inner extractor never rejects. That's fine; it adds no overhead other than the type-level wrapper.

However, be careful: if you use WithRejection with an extractor that can succeed but you also want to perform additional validation inside the handler and return a rejection-like error, WithRejection won't help with that. It only handles the rejection produced by the extractor itself, not errors you create after successful extraction. For that, you'd use Result or a custom response inside the handler.

Common mistakes when using WithRejection

Forgetting to import the correct rejection type

Each extractor has its own rejection enum, and the From impl's parameter type must match exactly. If you write impl From<QueryRejection> for MyError but the extractor is Path<...>, the compiler will complain. Always double-check which rejection type corresponds to your extractor.

Assuming the conversion runs for every error in the handler

The From conversion only runs when the extractor itself fails. If the extractor succeeds and later code in the handler returns an error (e.g., by returning Err from a Result), the conversion is not involved. You need a different mechanism for that, such as a custom IntoResponse implementation or a Result in the handler signature.

Trying to pass a function as the second generic

A common mistake is writing WithRejection<Query<PageParams>, fn(QueryRejection) -> Response> and destructuring the second tuple element as the function. That does not compile: the second generic must be a type implementing From<QueryRejection> and IntoResponse, and a function pointer implements neither. The second tuple element is a PhantomData, not a callable. Define a small response type with a From impl instead, as shown above.

Overcomplicating the mapping for simple cases

If you just need a simple default error response for all rejections from an extractor, you might not need WithRejection at all. You could implement IntoResponse for your custom rejection and let Axum's default handler use it. However, for built-in extractors, you can't easily change their rejection types, so WithRejection is the way to go when you need a different response than the built-in default.

Don't mix up response and rejection:

A rejection is not a response. It is an intermediate error type that Axum will turn into a response if you don't intercept it. When you use WithRejection, you are responsible for turning the rejection into a proper response: your response type's From impl must build a value that implements IntoResponse. If the From impl produces something that is not a valid response (like a bare String), the code won't compile. Always build a Response (for example with .into_response()) inside the From impl.

Practical real-world usage

In production APIs, consistent error responses are critical. Many teams define an ApiError type and a standard JSON error format like the one we used earlier. WithRejection lets you enforce that format across all extractor failures without scattering boilerplate code in every handler.

For example, you might have:

  • A Query extractor that maps to 422 with {"error":"invalid_query_params"}.
  • A Json extractor that maps to 400 with {"error":"invalid_json"}.
  • A custom Auth extractor that maps to 401 with {"error":"unauthorized"}.

All of these can use separate response types that share a common helper to build the JSON body. This keeps error handling uniform and easy to maintain.

Summary

WithRejection is a powerful tool from axum-extra that gives you fine-grained control over what happens when an extractor rejects a request. Instead of relying on Axum's default plain-text error responses, you can define a small response type whose From impl turns a rejection into exactly the HTTP response your API contract requires. You can use it with any extractor, built-in or custom, and you can compose it with other extractors and wrappers.

The key insight is that WithRejection moves the error-response logic out of the handler and into a separate, reusable response type. This separation makes your handlers cleaner, your error format consistent, and your API more predictable for clients. If you find yourself writing if let Err(...) = extractor::from_request(...) inside every handler, WithRejection is the idiom you should adopt.

Next time you need to customize the error response for a failing extractor, remember that you don't have to change the extractor itself or pollute your handlers - just wrap it in WithRejection and point it to a response type that speaks your API's error language.