Default rejection behavior

What Axum does on its own when an extractor fails and how to read the status code and plain text body it returns

An extractor is a piece of a handler that pulls one part out of an incoming request. Path pulls a value out of the URL path, Query pulls values out of the query string, and Json pulls a value out of the request body. Each extractor can fail. When one fails, Axum calls that failure a rejection, and it turns the rejection into an HTTP response all by itself. The handler never runs, and no extra code is needed to make this happen.

Where This Fits

The thiserror derive page showed how a project builds its own error type with a derive macro. That error type covers mistakes the handler itself finds while it runs. This page covers the step before the handler runs at all. When an extractor cannot do its job, there is no handler result to return, so Axum answers the request on its own. Think of it like a guard at a door who turns away a visitor with the wrong ticket before anyone inside is bothered.

The Smallest Working Example

Here is a route that reads a user id from the path. The id is declared as i32, a whole number. Send a request with a word instead of a number and watch what Axum does without any error handling code from you.

// src/lib.rs
use axum::{extract::Path, routing::get, Router};

pub fn app() -> Router {
    Router::new().route("/users/{id}", get(get_user))
}

async fn get_user(Path(id): Path<i32>) -> String {
    format!("User {}", id)
}
// src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    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 Cargo.toml file needs these dependencies:

# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

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

Run the server with cargo run. A good request returns the user line:

curl http://127.0.0.1:3000/users/42
User 42

A bad request never reaches the handler. Axum answers it directly:

curl http://127.0.0.1:3000/users/abc
Invalid URL: Cannot parse `abc` to a `i32`

The response carries status 400. That is the whole default behavior in one picture. The extractor tried to turn the text abc into an i32, that failed, and Axum sent back a short plain text explanation with a 400 status code.

Seeing the Default in Action:

If curl http://127.0.0.1:3000/users/42 prints User 42 and curl http://127.0.0.1:3000/users/abc prints a 400 response with the text about parsing abc, the default rejection behavior is working. Nothing else needs to be configured.

What a Rejection Is

A rejection is a value that describes one specific way an extractor failed. Every extractor has its own rejection type. Path fails with a PathRejection, Query fails with a QueryRejection, and Json fails with a JsonRejection. Each of those types knows how to turn itself into a response, because each one implements IntoResponse, the trait Axum uses to convert a value into an HTTP response.

The word rejection is worth pinning down, because beginners often mix it up with two other things. A rejection is not a Rust Err returned by the handler. The handler returns nothing at all when an extractor rejects, because the handler never starts. A rejection is also not a panic. Nothing crashes, and the server keeps running and keeps serving other requests. It is a normal, expected outcome: the request did not carry data the handler could use, so Axum answered with an error response instead of calling the handler.

Rejection Is Not a Crash:

A rejected request does not stop the server and does not print a panic message. The server logs nothing by default and carries on with the next request. If you see the process exit or a panic trace, something else went wrong.

The Default Response Shape

Every default rejection response has the same shape. It is plain text, not JSON. Its content type is text/plain; charset=utf-8. Its body has two parts joined by a colon and a space. The first part is a fixed message that names the kind of failure. The second part is the detail from the underlying error, which changes with the request.

For the path example above, the fixed part is Invalid URL and the detail is Cannot parse `abc` to a `i32`. The fixed part stays the same for every bad id. The detail changes: send /users/xyz and the detail names xyz instead of abc. A client program that reads these responses should match on the status code and the fixed first part, never on the full body text, because the detail part moves around.

The status code is part of the shape too, and it is chosen per failure, not per extractor. A JSON body that is not valid JSON gets 400, while a JSON body that is valid JSON but has the wrong shape gets 422. Both come from the same Json extractor. The table in the next section lists every default you will meet in this cluster of pages.

The Default Status Codes and Bodies

This table was checked by running real requests against Axum 0.8.9. The status code and the fixed first part of the body are stable. The detail after the colon depends on the exact input, so the table shows one real example of it.

FailureStatusBody (fixed part plus one real detail)
Path segment cannot be parsed into the declared type400Invalid URL: Cannot parse abcto ai32``
JSON body is not valid JSON400Failed to parse the request body as JSON: age: expected value at line 1 column 22
JSON body is valid JSON but the wrong shape422Failed to deserialize the JSON body into the target type: age: invalid type: string "thirty", expected u32 at line 1 column 29
JSON request is missing the JSON content type, or the content type is wrong415Expected request with Content-Type: application/json``
Query string cannot be parsed into the declared type400Failed to deserialize query string: page: invalid digit found in string

Read the JSON rows carefully, because they show why two different status codes exist for one extractor. A body that is not JSON at all is a syntax problem, and syntax problems get 400. A body that parses as JSON but does not fit the target type is a shape problem, and shape problems get 422. The number 422 means the request was understood but its content could not be processed, which fits a well formed body with a wrong field type. The content type row has no detail after a colon. Its body is one fixed sentence, because there is no underlying parse error to report.

Plain Text, Not JSON:

Default rejection bodies are plain text. A client that always parses error bodies as JSON will fail on these responses, because Invalid URL: ... is not JSON. That mismatch is the main reason projects later replace the defaults with their own JSON shape.

Why the Handler Never Runs

Axum runs the extractors in the order the handler lists them, from left to right, before the handler body starts. Each extractor either produces its value or rejects. The first rejection stops the chain. The remaining extractors do not run, and the handler does not run either. Axum takes the rejection, converts it into a response, and sends that response back.

This order matters when a handler has more than one extractor. A handler that takes both a Path and a Json body and receives a bad id and a bad body answers with the path rejection, because the path extractor runs first. The JSON body is never read. That behavior was checked by running a request with both parts wrong: the response was the 400 path message, not the JSON message. Fix the path and send the same bad body again, and the JSON rejection appears instead.

// src/lib.rs
use axum::{
    extract::{Json, Path},
    routing::post,
    Router,
};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
    name: String,
    age: u32,
}

pub fn app() -> Router {
    Router::new().route("/both/{id}", post(both_extractors))
}

async fn both_extractors(Path(id): Path<i32>, Json(payload): Json<CreateUser>) -> String {
    format!("User {} named {}", id, payload.name)
}

Send a request with a bad id and a malformed body:

curl -X POST http://127.0.0.1:3000/both/abc -H "Content-Type: application/json" -d '{"name":"Asha","age":}'

The response is the path rejection:

Invalid URL: Cannot parse `abc` to a `i32`

Change only the id to 42 and send the same body, and the JSON rejection appears:

Failed to parse the request body as JSON: age: expected value at line 1 column 22

The handler body, the line that formats User {} named {}, never ran in either case. There was no user id and no payload to format with, so running it would have been meaningless. Axum short circuits the request instead.

The Concept Behind the Default

The default exists because a handler cannot do its own input checking before its inputs exist. The handler signature promises that by the time the body runs, every extractor argument already holds a real value of the declared type. A Path<i32> argument is a genuine i32 inside the handler, never a string that might fail to parse. That promise is what makes handler code simple to write. The price of the promise is that failures have to be handled somewhere else, and the default rejection response is that somewhere else.

Think of the handler signature as a contract. The route says which pieces of the request the handler needs, and the types say what shape each piece must have. Axum checks the contract before calling the handler. If the request breaks the contract, Axum answers the client itself. If the request keeps the contract, the handler runs with values it can trust.

The Contract Idea:

Inside the handler, Path<i32> is always a valid i32. No parsing code and no error branch for a bad id is needed there. That guarantee is the point of extractors, and rejections are the mechanism that keeps the guarantee honest.

Why Axum Answers Instead of Crashing or Waiting

Three other designs were possible, and each one is worse for a beginner. Axum could panic on a bad id, but a panic would kill the request handling and print a frightening trace for an ordinary client mistake. Axum could pass the raw string into the handler and let every handler parse it, but then every handler would repeat the same parsing and error code. Axum could silently substitute a default value, but a made up id would be worse than an error, because the handler would act on data the client never sent.

Answering with a 400 or 422 response is the honest middle path. The client sent something the server cannot use, so the server says so, in plain words, with a status code the client can act on. The handler stays clean, the server stays up, and the mistake stays visible.

A Richer Complete Example

The smallest example showed one extractor. A realistic route uses all three, so here is a small user API with a path id, a JSON body, and a query string, all relying on defaults. Nothing in this file handles errors. Every failure below comes from Axum.

// src/lib.rs
use axum::{
    extract::{Json, Path, Query},
    http::StatusCode,
    routing::{get, post},
    Router,
};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct CreateUser {
    name: String,
    age: u32,
}

#[derive(Serialize)]
struct User {
    id: i32,
    name: String,
    age: u32,
}

#[derive(Deserialize, Debug)]
struct Search {
    query: String,
    page: u32,
}

pub fn app() -> Router {
    Router::new()
        .route("/users/{id}", get(get_user))
        .route("/users", post(create_user))
        .route("/search", get(search))
}

async fn get_user(Path(id): Path<i32>) -> Json<User> {
    Json(User {
        id,
        name: "Asha".to_string(),
        age: 30,
    })
}

async fn create_user(Json(payload): Json<CreateUser>) -> (StatusCode, Json<User>) {
    (
        StatusCode::CREATED,
        Json(User {
            id: 1,
            name: payload.name,
            age: payload.age,
        }),
    )
}

async fn search(Query(params): Query<Search>) -> String {
    format!("Searching for {} on page {}", params.query, params.page)
}

The serde derive macros turn the structs into types that JSON and query parsing can fill in. CreateUser is the shape a POST body must have. Search is the shape the query string must have. User is the shape the server sends back. None of these structs knows anything about rejections. That knowledge lives in the extractors.

Run the server and try each failure in turn. Each request below is a different rejection, and each one is answered without the handler running.

curl http://127.0.0.1:3000/users/abc
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: application/json" -d '{"name":"Asha","age":}'
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: application/json" -d '{"name":"Asha","age":"thirty"}'
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: text/plain" -d '{"name":"Asha","age":30}'
curl "http://127.0.0.1:3000/search?query=rust&page=abc"

The responses, in order, are 400 for the bad id, 400 for the malformed JSON, 422 for the wrong field type, 415 for the wrong content type, and 400 for the bad page number. The good versions of the same requests return 200 or 201 with JSON or text bodies. The same file produces both outcomes, and the only difference is whether the request data fits the declared types.

A Missing Route Is Not a Rejection:

Requesting a path with no route at all, such as /users/ with no id segment or /nothere, returns 404 with an empty body. That 404 comes from routing, not from an extractor, and no rejection is involved. Do not expect a rejection message for a URL the router never matched.

Reading a Default Response as a Client

A client program that talks to this API needs a small decision rule for rejection responses. The status code says what kind of problem it is. A 400 means the request itself was malformed or unparsable. A 415 means the request used the wrong content type. A 422 means the request was well formed but did not fit the expected shape. The body text adds the detail a human needs to fix the request, such as which field had the wrong type and where the JSON broke.

The plain text body is easy for a human to read in a terminal, and awkward for a program to parse. That awkwardness is deliberate in the sense that Axum keeps its default simple. A program that needs structured errors should not parse the default text. It should use the override described on the custom rejection override page, which replaces these plain text bodies with one JSON shape for every error.

How the Request Flows Through a Rejection

Here is the full path a request takes when an extractor rejects, in plain text:

Client sends request
        |
        v
Router matches path and method
        |
        v
First extractor runs (left to right)
        |
        v
Extractor fails and produces a rejection value
        |
        v
Remaining extractors and handler are skipped
        |
        v
Rejection is turned into a response (status plus plain text body)
        |
        v
Client receives the error response

The happy path differs at exactly one step. When every extractor succeeds, the handler runs and its return value becomes the response. Everything before that step is identical. That shared start is why the default feels invisible on good requests and obvious on bad ones.

Testing the Default Behavior

Defaults are easy to test because no server needs to run. The test below builds the router, sends requests straight through it with oneshot, and checks the status codes. oneshot comes from the tower crate, which the test needs as a dev dependency.

# Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/default_rejection_test.rs
use axum::{
    body::{to_bytes, Body},
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn body_text(uri: &str) -> (StatusCode, String) {
    let response = app()
        .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = response.status();
    let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).to_string())
}

#[tokio::test]
async fn good_id_returns_user() {
    let (status, body) = body_text("/users/42").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("42"));
}

#[tokio::test]
async fn bad_id_is_rejected_with_400() {
    let (status, body) = body_text("/users/abc").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("Cannot parse `abc` to a `i32`"));
}

#[tokio::test]
async fn unknown_route_is_404_not_a_rejection() {
    let (status, _) = body_text("/nothere").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

The helper body_text builds a request, pushes it through the router with oneshot, and reads the whole response body back into a string. oneshot sends exactly one request through a service and waits for the response, with no network involved. Each test then checks one behavior: a good id works, a bad id is rejected with 400, and an unknown route is a plain 404 rather than a rejection. Run the tests with cargo test and all three pass.

Tests That Prove the Default:

These tests pass with no error handling code in the project at all. That is the point. The default rejection behavior is part of Axum itself, so it is testable the moment the route exists.

Common Beginner Mistakes

Expecting the Handler to Run on Bad Input

// Wrong - this line never runs for /users/abc
async fn get_user(Path(id): Path<i32>) -> String {
    println!("Looking up user {}", id);
    format!("User {}", id)
}

Beginners sometimes add logging or a fallback inside the handler and wonder why it never fires for bad input. The extractor runs first, so the println! line is never reached when the id cannot be parsed. Anything the handler should do on bad input has to live outside the handler, in an override, not inside the handler body.

Treating the Default Body as JSON

// Wrong - the default body is plain text, not JSON
let error: serde_json::Value = serde_json::from_str(&body).unwrap();

Parsing a default rejection body as JSON fails, because the body is text like Invalid URL: .... Code that reads error responses must either check the content type first or handle plain text. If every error needs to be JSON, the fix is to override the rejection, not to parse harder.

Assuming Every Bad Request Gets 400

A JSON body with the wrong field type returns 422, and a JSON request with the wrong content type returns 415. Code that treats every client error as 400 will misread those two cases. The status code carries meaning, so match on the exact code the table lists instead of assuming one code covers all rejections.

Confusing a 404 With a Rejection

A request to a path with no route returns 404 with an empty body. That is routing saying no route matched. A rejection only happens after a route matched and an extractor failed. The two look similar from the outside, a failed request with a 4xx status, but they come from different layers and carry different bodies.

Final Complete Example

Here is the whole project in one place: the router with three extractors, the server entry point, the dependencies, and a test that checks the default for a bad id.

// src/lib.rs
use axum::{
    extract::{Json, Path, Query},
    http::StatusCode,
    routing::{get, post},
    Router,
};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct CreateUser {
    name: String,
    age: u32,
}

#[derive(Serialize)]
struct User {
    id: i32,
    name: String,
    age: u32,
}

#[derive(Deserialize, Debug)]
struct Search {
    query: String,
    page: u32,
}

pub fn app() -> Router {
    Router::new()
        .route("/users/{id}", get(get_user))
        .route("/users", post(create_user))
        .route("/search", get(search))
}

async fn get_user(Path(id): Path<i32>) -> Json<User> {
    Json(User {
        id,
        name: "Asha".to_string(),
        age: 30,
    })
}

async fn create_user(Json(payload): Json<CreateUser>) -> (StatusCode, Json<User>) {
    (
        StatusCode::CREATED,
        Json(User {
            id: 1,
            name: payload.name,
            age: payload.age,
        }),
    )
}

async fn search(Query(params): Query<Search>) -> String {
    format!("Searching for {} on page {}", params.query, params.page)
}
// src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    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();
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

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

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/default_rejection_test.rs
use axum::{
    body::{to_bytes, Body},
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn bad_id_is_rejected_with_400() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/users/abc")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    let body = String::from_utf8_lossy(&bytes).to_string();
    assert!(body.contains("Cannot parse `abc` to a `i32`"));
}

Run the server with cargo run and the tests with cargo test. Good requests return users, bad requests return short plain text errors, and no error handling code was written anywhere in the project.

Summary

The default rejection behavior is a trade. The handler gives up any say over malformed input, and in return it gets a guarantee that its arguments are always real values of the declared types. Axum keeps its side of the trade by answering bad requests itself, with a status code chosen per failure and a plain text body that names the problem and the detail. The most useful habit this page teaches is reading the status code first and the body second, because the code says what kind of problem it is and the body says which value caused it. Once that reading habit is in place, the decision of whether to keep the defaults or replace them with one JSON shape becomes a question about who reads the errors, humans in a terminal or programs parsing responses, and that question is what the rest of this cluster answers one extractor at a time.