Custom rejection override
How to take control of extractor failures with Result and map each rejection into the shared JSON error shape
So far every rejection in this cluster has been answered by Axum itself, with a plain text body. That default is fine for a human reading a terminal, and wrong for a client program that expects every error to arrive as JSON. This page shows how to take control. Wrap the extractor in a Result, catch the rejection in the handler, and turn it into the same JSON error shape the rest of the project uses. The handler runs, the rejection becomes your error type, and the client sees one consistent shape for every failure.
Where This Fits
The query extractor rejection page showed the last of the three default rejections. All three share one problem: their bodies are plain text while the project error type answers with JSON. This page closes that gap. It takes the defaults apart and rebuilds them in the shared shape, so a bad id, a bad body, and a bad query all come out looking like any other error in the project.
The Smallest Working Example
Here is the smallest override. The handler takes Result<Path<i32>, PathRejection> instead of Path<i32>. When the id parses, the handler runs as normal. When it does not parse, the handler still runs, receives the rejection as the Err value, and returns it as the shared error type.
// src/lib.rs
pub mod errors;
use axum::{
extract::{rejection::PathRejection, Path},
routing::get,
Router,
};
use crate::errors::AppError;
pub fn app() -> Router {
Router::new().route("/users/{id}", get(get_user))
}
async fn get_user(result: Result<Path<i32>, PathRejection>) -> Result<String, AppError> {
match result {
Ok(Path(id)) => Ok(format!("User {}", id)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid user id in the path: {}",
rejection
))),
}
}
The shared error type lives in its own file. Only the piece this page needs is shown here: the ValidationError variant, which carries a human readable message and answers with status 422 and a JSON body shaped like {"error": "<message>"}. The full error type, with its other variants and its response mapping, belongs to the custom error pages of this project.
// src/errors.rs
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
// The response mapping turns ValidationError into
// status 422 with a JSON body {"error": "<message>"}.
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"
The main.rs file is the same small entry point used on the other pages of this cluster. It builds the router, binds a listener on port 3000, and serves the app.
// 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();
}
Run the server with cargo run. A good id works as before:
curl http://127.0.0.1:3000/users/42
User 42
A bad id now returns JSON instead of plain text:
curl http://127.0.0.1:3000/users/abc
{"error":"Invalid user id in the path: Cannot parse `abc` to a `i32`"}
The status changes from 400 to 422, because the shared error type maps every validation failure to 422. A bad id is still a client mistake, and the message still says so. What the override gives the client is the same JSON error shape for a rejected id as for any other error in the project.
Seeing the Override Work:
If /users/abc returns 422 with a JSON body that has an error key, the override is working. Compare it with the plain text body from the default pages. Different status and different shape, same meaning: the id was not a number.
How Wrapping an Extractor in Result Works
An extractor type such as Path<i32> implements a trait that tells Axum how to pull a value out of a request. That trait has an associated rejection type, and for Path<i32> the rejection type is PathRejection. When the handler declares the extractor directly, Axum turns a rejection into a response on its own. When the handler declares Result<Path<i32>, PathRejection> instead, Axum hands the Ok or Err value to the handler and lets the handler decide what to do with it.
The word Result here is the same Result used everywhere in Rust. It holds either a success value or an error value. Wrapping the extractor does not change how extraction works. The same parse runs, and the same failure produces the same rejection value. The only change is who receives that value. Without the wrapper, Axum receives it and answers directly. With the wrapper, the handler receives it and answers in its own way.
The handler return type changes to match. A handler that used to return String now returns Result<String, AppError>, because the failure branch needs a type to return. AppError implements IntoResponse, so returning it as an Err turns it into the JSON error response, exactly as it does when a handler returns an AppError for its own reasons. That shared return type is what makes the override consistent: a rejection and a handler error travel through the same type to the same response shape.
The Wrapper Changes Who Answers, Not What Failed:
The rejection value is identical with or without the wrapper. The parse failure, the variant, and the detail inside it are all the same. Only the response changes, because a different piece of code turns the rejection into a response.
The Rejection Display Text
The message inside the JSON body comes from formatting the rejection with {}. That formatting prints the rejection's own description, which is usually the same text as the default body, minus the fixed first part in some cases. The difference is small but worth seeing, because the override message is built from this text.
For a bad path id, the default body was Invalid URL: Cannot parse abcto ai32, while the rejection formatted with `{}` prints only `Cannot parse `abc` to a `i32. The override message adds its own prefix, Invalid user id in the path: , so the client still gets a readable sentence. For a JSON rejection, the formatted text is the full default body, including its fixed first part. For a query rejection, the same holds. The rule is simple: format the rejection, read what it prints, and write your prefix around the real text rather than guessing it.
Overriding a Path Rejection
The path override from the smallest example is the pattern every other override follows. Match on the Result, return the value on success, and map the rejection to a ValidationError on failure. The message names the field and includes the rejection detail, so the client can see which value failed.
// src/lib.rs
pub mod errors;
use axum::{
extract::{rejection::PathRejection, Path},
routing::get,
Router,
};
use crate::errors::AppError;
pub fn app() -> Router {
Router::new().route("/users/{id}", get(get_user))
}
async fn get_user(result: Result<Path<i32>, PathRejection>) -> Result<String, AppError> {
match result {
Ok(Path(id)) => Ok(format!("User {}", id)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid user id in the path: {}",
rejection
))),
}
}
A request to /users/abc returns status 422 with the body {"error":"Invalid user id in the path: Cannot parse abcto ai32"}. A request to /users/42 returns 200 with User 42. The handler body is short because the success branch is one line and the failure branch is one line. The match makes both branches visible, which is the point. A reader can see exactly what happens for a good id and for a bad one.
Overriding a Json Rejection
The JSON override follows the same pattern, with one extra decision. A JsonRejection has four variants, and each one deserves its own message, because each one needs a different fix from the client. The match below gives a specific message to the two most common failures and falls back to a general message for the rest.
// src/lib.rs
pub mod errors;
use axum::{
extract::{rejection::JsonRejection, Json},
http::StatusCode,
routing::post,
Router,
};
use serde::Deserialize;
use serde_json::json;
use crate::errors::AppError;
#[derive(Deserialize)]
struct CreateUser {
name: String,
age: u32,
}
pub fn app() -> Router {
Router::new().route("/users", post(create_user))
}
async fn create_user(
result: Result<Json<CreateUser>, JsonRejection>,
) -> Result<(StatusCode, Json<serde_json::Value>), AppError> {
match result {
Ok(Json(payload)) => Ok((
StatusCode::CREATED,
Json(json!({ "id": 1, "name": payload.name, "age": payload.age })),
)),
Err(JsonRejection::JsonSyntaxError(_)) => Err(AppError::ValidationError(
"The request body is not valid JSON.".to_string(),
)),
Err(JsonRejection::MissingJsonContentType(_)) => Err(AppError::ValidationError(
"Send the request with Content-Type: application/json.".to_string(),
)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid JSON body: {}",
rejection
))),
}
}
The patterns need care. JsonSyntaxError and MissingJsonContentType are tuple variants, so their patterns carry (_) for the inner value the handler does not need. The last arm catches everything else, which covers the wrong shape variant and the body read failure. That catch-all arm matters, because the rejection enum is marked so that Axum may add variants in a future version. A match with no catch-all would fail to compile when a new variant appears. The catch-all keeps the handler working.
Run the server and try each failure. The responses below were checked by running real requests against Axum 0.8.9.
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: application/json" -d '{"name":"Asha","age":}'
{"error":"The request body is not valid JSON."}
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: text/plain" -d '{"name":"Asha","age":30}'
{"error":"Send the request with Content-Type: application/json."}
curl -X POST http://127.0.0.1:3000/users -H "Content-Type: application/json" -d '{"name":"Asha","age":"thirty"}'
{"error":"Invalid JSON body: Failed to deserialize the JSON body into the target type: age: invalid type: string \"thirty\", expected u32 at line 1 column 29"}
All three return status 422, because the override maps every JSON rejection to ValidationError, and that variant maps to 422. The default gave these three failures the statuses 400, 415, and 422. The override deliberately flattens them into one status, because the shared error shape has one status for validation problems. That flattening is a trade, and the next section weighs it.
The Override Flattens the Json Status Codes:
The default distinguishes a syntax failure with 400, a wrong content type with 415, and a wrong shape with 422. The override maps all three to 422 through ValidationError. That is the chapter contract: one shape and one status for validation problems. If a project needs the three codes preserved, the override should return a custom response per variant instead of routing through ValidationError.
Overriding a Query Rejection
The query override is the shortest of the three, because QueryRejection has only one variant. The match still names the field that failed through the rejection detail.
// src/lib.rs
pub mod errors;
use axum::{
extract::{rejection::QueryRejection, Query},
routing::get,
Router,
};
use serde::Deserialize;
use crate::errors::AppError;
#[derive(Deserialize, Debug)]
struct Search {
query: String,
page: u32,
}
pub fn app() -> Router {
Router::new().route("/search", get(search))
}
async fn search(result: Result<Query<Search>, QueryRejection>) -> Result<String, AppError> {
match result {
Ok(Query(params)) => Ok(format!(
"Searching for {} on page {}",
params.query, params.page
)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid query string: {}",
rejection
))),
}
}
A request to /search?query=rust&page=abc returns status 422 with the body {"error":"Invalid query string: Failed to deserialize query string: page: invalid digit found in string"}. The message repeats the word query twice, once in the prefix and once in the rejection text. That repetition is harmless, and it keeps the full detail from the rejection. A shorter prefix such as Bad search request: would read better and lose nothing, because the detail still names the field.
The Shorter Form With map_err
The match form is the clearest version, and it is the one to reach for when each failure needs its own message. When the override is the same for every failure, the map_err form is shorter. It converts the Err value with a closure and then uses ? to return early on failure.
// src/lib.rs
pub mod errors;
use axum::{
extract::{rejection::PathRejection, Path},
routing::get,
Router,
};
use crate::errors::AppError;
pub fn app() -> Router {
Router::new().route("/users/{id}", get(get_user))
}
async fn get_user(result: Result<Path<i32>, PathRejection>) -> Result<String, AppError> {
let Path(id) = result.map_err(|rejection| {
AppError::ValidationError(format!("Invalid user id in the path: {}", rejection))
})?;
Ok(format!("User {}", id))
}
The map_err call runs the closure only when the result is an Err. The closure turns the rejection into an AppError::ValidationError. The ? operator then returns that error from the handler immediately, so the lines below it only run when the extraction succeeded. The let Path(id) = ... line pulls the i32 out of the Path wrapper. This form compiles to the same behavior as the match form, with less code. Use the match form when failures need different messages, and the map_err form when one message covers them all.
Do Not Destructure the Result in the Parameter List:
Writing the parameter as Path(id): Result<Path<i32>, PathRejection> does not compile. The parameter must be named as a whole value, such as result: Result<Path<i32>, PathRejection>, and the Path wrapper is pulled apart inside the handler body. The compiler error for the wrong form says the pattern expected a Result and found a Path, which is the hint that the value has not been unwrapped yet.
What the Override Does Not Change
Wrapping an extractor changes the response, and nothing else. The extractor still runs first, still runs in parameter order, and still stops the chain on failure. A handler with two wrapped extractors still sees the first failure only. The handler body still never runs on a failure, because the failure is returned before the body starts in any meaningful sense: the handler function is called with the Err value, but the success branch never executes. The route pattern, the declared types, and the parsing rules are all untouched.
The override also does not change the status code of the success path. A good request still returns 200 or 201 exactly as before. The failure response changes in two ways: its shape, from plain text to the shared JSON shape, and its status, from the default 400 to 422, because the shared error type maps validation failures to 422.
The Concept Behind the Override
The default rejection is Axum speaking for the handler. The override is the handler speaking for itself. The mechanism that makes the switch possible is the Result wrapper, which turns a rejection from an automatic response into an ordinary value the handler can inspect. Once the rejection is a value, all of Rust's normal error handling applies: match on it, map it, attach context to it, and return it as the project's own error type.
Think of the default as a form letter and the override as a handwritten reply. The form letter is fast and always correct, but it speaks in Axum's voice and in plain text. The handwritten reply takes a few lines of code, but it speaks in the project's voice and in the project's shape. A public API needs the handwritten reply, because its clients read errors as data. An internal tool or a learning project can keep the form letter.
Why One Shared Shape Matters
A client that talks to an API writes one error handling path. It checks the status code, reads the error field, and shows the message or retries. That single path only works when every error arrives in the same shape. The default rejections break it, because they arrive as plain text while handler errors arrive as JSON. The client would need a second path for plain text, plus a rule for which endpoints return which shape. The override removes that second path. Every failure, whether the handler found it or an extractor found it, arrives as {"error": "<message>"} with a status code from the same small set.
The cost is a few lines per handler and the flattening of the JSON status codes noted above. The benefit is that no client ever has to guess the shape of an error. For a public API, that trade is worth making on every route that takes input.
How the Request Flows Through an Override
Here is the path a request takes when a wrapped extractor rejects, in plain text:
Client sends request with a bad id
|
v
Router matches /users/{id} and stores "abc" as id
|
v
Path<i32> tries to parse "abc" into an i32
|
v
Parsing fails, the handler receives Err(PathRejection)
|
v
Handler maps the rejection to AppError::ValidationError
|
v
AppError becomes a 422 response with a JSON error body
|
v
Client receives {"error": "..."}
The good path differs at the parse step. When parsing succeeds, the handler receives Ok(Path(id)) and returns the user line. The extractor runs the same way in both paths. Only the destination of the rejection changes.
Testing the Override
The tests below check that a bad id returns the JSON shape and that a good id still works. They use oneshot from the tower crate, which needs to be a dev dependency.
# Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/rejection_override_test.rs
use axum::{
body::{to_bytes, Body},
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn get(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_still_works() {
let (status, body) = get("/users/42").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "User 42");
}
#[tokio::test]
async fn bad_id_returns_json_error_shape() {
let (status, body) = get("/users/abc").await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body,
r#"{"error":"Invalid user id in the path: Cannot parse `abc` to a `i32`"}"#
);
let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(
parsed["error"],
"Invalid user id in the path: Cannot parse `abc` to a `i32`"
);
}
#[tokio::test]
async fn bad_query_returns_json_error_shape() {
let (status, body) = get("/search?query=rust&page=abc").await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(body.contains(r#""error":"Invalid query string:"#));
}
The bad id test asserts the exact body, and then parses the body as JSON to prove the shape is real JSON with an error key, not text that happens to look like JSON. The query test checks the shape with contains, because the full detail is longer. Run the tests with cargo test.
Tests That Prove the Shape:
Parsing the error body back into JSON in the test is the strongest check on this page. A plain text default would fail that parse, so the test proves the override changed the shape rather than just the words.
Common Beginner Mistakes
Forgetting the Rejection Type in the Result
// Wrong - the error type must be the extractor's rejection type
async fn get_user(result: Result<Path<i32>, AppError>) -> Result<String, AppError> {
Axum only knows how to hand a PathRejection to the handler. Declaring the error type as anything else fails to compile, because the handler signature no longer matches what Axum can provide. The error type in the Result must be the rejection type, and the return type is where AppError belongs.
Returning the Rejection Directly
// Wrong - a PathRejection answers with the plain text default
async fn get_user(result: Result<Path<i32>, PathRejection>) -> Result<String, PathRejection> {
let Path(id) = result?;
Ok(format!("User {}", id))
}
Returning the rejection as the handler error compiles, but it defeats the override. The rejection turns itself into the plain text default response, exactly as if no override existed. The point of the wrapper is to convert the rejection into AppError, not to pass it through unchanged.
Importing the Wrong Rejection Type
// Wrong - JsonRejection cannot catch a Path failure
use axum::extract::rejection::JsonRejection;
async fn get_user(result: Result<Path<i32>, JsonRejection>) -> Result<String, AppError> {
Each extractor has its own rejection type, and they are not interchangeable. Path fails with PathRejection, Json with JsonRejection, and Query with QueryRejection. The import must match the extractor in the same Result.
Dropping the Detail From the Message
// Wrong - the client cannot tell which value failed
Err(AppError::ValidationError("Invalid input.".to_string()))
A message with no detail forces the client to guess what went wrong. Include the rejection in the message with {} so the field name and the reason survive. The detail is the most useful part of the error.
Overriding Every Handler When a Custom Extractor Would Do
The Result wrapper is the right tool when one handler needs its own message. When every handler in a project needs the same override, repeating the wrapper on each one is tedious and easy to forget. In that case a custom extractor that wraps the built in one and returns the shared error shape is the better tool. That pattern is a larger design decision and belongs to the project as a whole, not to a single handler.
Final Complete Example
Here is the whole project in one place: all three overrides, the small error file, the server entry point, the dependencies, and the test file.
// src/errors.rs
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
This is the file the project already has from the custom error pages, shown here in full so the final example runs as written. The override on this page only uses the ValidationError line. The other two arms are unchanged from how the custom error pages built them.
// src/lib.rs
pub mod errors;
use axum::{
extract::{
rejection::{JsonRejection, PathRejection, QueryRejection},
Json, Path, Query,
},
http::StatusCode,
routing::{get, post},
Router,
};
use serde::Deserialize;
use serde_json::json;
use crate::errors::AppError;
#[derive(Deserialize)]
struct CreateUser {
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(result: Result<Path<i32>, PathRejection>) -> Result<String, AppError> {
match result {
Ok(Path(id)) => Ok(format!("User {}", id)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid user id in the path: {}",
rejection
))),
}
}
async fn create_user(
result: Result<Json<CreateUser>, JsonRejection>,
) -> Result<(StatusCode, Json<serde_json::Value>), AppError> {
match result {
Ok(Json(payload)) => Ok((
StatusCode::CREATED,
Json(json!({ "id": 1, "name": payload.name, "age": payload.age })),
)),
Err(JsonRejection::JsonSyntaxError(_)) => Err(AppError::ValidationError(
"The request body is not valid JSON.".to_string(),
)),
Err(JsonRejection::MissingJsonContentType(_)) => Err(AppError::ValidationError(
"Send the request with Content-Type: application/json.".to_string(),
)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid JSON body: {}",
rejection
))),
}
}
async fn search(result: Result<Query<Search>, QueryRejection>) -> Result<String, AppError> {
match result {
Ok(Query(params)) => Ok(format!(
"Searching for {} on page {}",
params.query, params.page
)),
Err(rejection) => Err(AppError::ValidationError(format!(
"Invalid query string: {}",
rejection
))),
}
}
// 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/rejection_override_test.rs
use axum::{
body::{to_bytes, Body},
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn get(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 bad_id_returns_json_error_shape() {
let (status, body) = get("/users/abc").await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body,
r#"{"error":"Invalid user id in the path: Cannot parse `abc` to a `i32`"}"#
);
}
Run the server with cargo run and the tests with cargo test. A bad id, a bad body, and a bad query all return 422 with a JSON body shaped like {"error": "<message>"}, while good requests still return their normal responses.
Summary
The override is a small change with a large effect on the client. One wrapper turns an automatic plain text answer into a value the handler owns, and one conversion turns that value into the same JSON shape every other error in the project uses. The decision framework is simple: keep the default when the errors are read by a human in a terminal, and override when the errors are read by a program. When overriding, match when failures need different messages and use the shorter mapping form when one message covers them all. Keep the rejection detail in the message, keep the catch-all arm so future variants still compile, and remember that the flattening of the JSON status codes is a deliberate trade for one consistent shape. Once every route answers failures the same way, the client needs only one error path, and that single path is the real product of this page.