Json deserialization rejection

Understand how Axum rejects invalid JSON request bodies and how to customize the error response using JsonRejection.

When a client sends JSON to your Axum server, the Json extractor does two jobs for you automatically. It reads the raw bytes from the request body, and it tries to convert those bytes into a Rust struct you have defined. If the body contains valid JSON that matches your struct, everything works and your handler runs with the typed data. If the body is not valid JSON, or if the JSON does not match the shape of your struct, Axum steps in and returns an error response before your handler is ever called.

That default behavior is safe and convenient, but it has a downside. The error response Axum sends back is generic. It tells the client "something went wrong" but it does not tell them which field was missing, whether the JSON had a syntax error, or whether the request simply forgot the Content-Type header. For a public API, or for a server where you want to log exactly what went wrong, you need to intercept the failure and handle it yourself.

That is what this page covers. You will learn what a JsonRejection is, what kinds of failures it represents, how to capture it in your handler, and how to turn it into a clear, useful response for the client.

The default failure behavior

Before learning how to customize the error, it helps to see what Axum does on its own. Assume you have a handler that creates a new user from a JSON payload.

use axum::{
    extract::Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}
async fn create_user(Json(payload): Json<CreateUser>) {
    // In a real app, you would insert the user into a database here.
    println!("Creating user with email: {}", payload.email);
}
let app = Router::new().route("/users", post(create_user));

When a client sends a valid request like this:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "secret"}'

The handler runs and prints the email address. The client gets a 200 OK response.

Now consider what happens when the client forgets the Content-Type header.

curl -X POST http://localhost:3000/users \
  -d '{"email": "alice@example.com", "password": "secret"}'

Axum rejects the request with a 415 Unsupported Media Type and a message like Expected request with `Content-Type: application/json` . Your handler never runs. The client receives an error, but they do not get a structured JSON error body that an application could parse programmatically.

The same automatic rejection happens for a malformed JSON body.

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": }'

Here the body is missing a value after "password", so it is not valid JSON syntax. Axum again returns 400 Bad Request with a generic message.

And if the JSON is valid but does not match your struct, Axum also rejects it.

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": 42, "password": "secret"}'

The email field is a String in the struct, but the client sent a number. Axum returns 422 Unprocessable Entity by default, because the JSON was syntactically correct but semantically wrong for the target type.

Why the default errors feel limiting:

Axum is doing the safe thing here. It prevents your handler from running with invalid data. But the automatic error messages are designed to be generic and minimal. If you want to return your own JSON error shape, log the details of the failure, or hide internal error information from clients, you need to take control of the rejection path.

What a JsonRejection actually is

Under the hood, the Json extractor implements a trait called FromRequest. During request handling, Axum calls the from_request method for every extractor in your handler's parameter list. If the extraction succeeds, Axum passes the value to your handler. If it fails, the extractor returns an error type called a "rejection."

For the Json extractor, that rejection type is JsonRejection. It is an enum, which means it can hold several different kinds of failure. Axum normally converts the rejection directly into an HTTP response and skips your handler. But you can change that by wrapping your extractor in Result.

use axum::{
    extract::Json,
    extract::rejection::JsonRejection,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) {
    match payload {
        Ok(Json(user)) => {
            println!("Creating user with email: {}", user.email);
        }
        Err(rejection) => {
            println!("Failed to parse JSON: {:?}", rejection);
        }
    }
}
let app = Router::new().route("/users", post(create_user));

This changes the behavior significantly. When you use Json<CreateUser> directly, Axum stops the request and returns an error if extraction fails. When you use Result<Json<CreateUser>, JsonRejection>, Axum still attempts the extraction, but if it fails, it passes the Err value into your handler instead of returning an automatic response. Your handler is now responsible for deciding what to send back to the client.

Think of it like a package delivery service. Normally, if a package is damaged during shipping, the service returns it to the sender without ever ringing your doorbell. Wrapping the extractor in Result is like telling the delivery service to hand you the damaged package anyway, so you can inspect it, file a report, and choose how to respond to the sender.

The handler now runs on failure:

This is the most important mental shift on this page. When you wrap an extractor in Result, your handler is called whether extraction succeeds or fails. That means your match arms are the only thing separating a successful request from a failed one. If you forget to handle the Err case, you might accidentally return a 200 OK response to a client that sent invalid JSON.

The four main rejection variants

JsonRejection has four specific variants that cover the most common failure scenarios. They are:

VariantWhat it meansTypical HTTP status
MissingJsonContentTypeThe request is missing the Content-Type: application/json header, or the header has an incompatible value.415 Unsupported Media Type
JsonSyntaxErrorThe body is not valid JSON syntax.400 Bad Request
JsonDataErrorThe body is valid JSON, but it does not match the target struct's fields or types.422 Unprocessable Entity
BytesRejectionThe server failed to read or buffer the request body. This usually indicates a network or server issue, not a client mistake.413 Payload Too Large if the body exceeded the size limit, otherwise 500 Internal Server Error

Each variant carries additional information that you can inspect. The MissingJsonContentType variant carries no extra information: it is a unit struct, so there is no received header value to inspect. The JsonSyntaxError and JsonDataError variants both wrap a serde_path_to_error::Error<serde_json::Error>, which records the path of the failing field as well as the underlying serde_json::Error. The BytesRejection variant wraps a lower-level error from the body buffering process.

Handling each variant explicitly in a match expression gives you precise control over the response.

Handling a missing Content-Type header

The most common mistake clients make when sending JSON is forgetting the Content-Type header. Without that header, Axum cannot know that the body should be interpreted as JSON.

Here is a handler that detects this specific failure and returns a clear error message.

use axum::{
    extract::Json,
    extract::rejection::JsonRejection,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) -> Response {
    match payload {
        Ok(Json(user)) => {
            println!("Creating user with email: {}", user.email);
            (
                StatusCode::CREATED,
                Json(json!({ "status": "created", "email": user.email })),
            )
                .into_response()
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            let error = json!({
                "error": {
                    "code": "missing_content_type",
                    "message": "This endpoint requires the header: Content-Type: application/json"
                }
            });
            (StatusCode::UNSUPPORTED_MEDIA_TYPE, Json(error)).into_response()
        }
        Err(JsonRejection::JsonSyntaxError(err)) => {
            let error = json!({
                "error": {
                    "code": "invalid_json_syntax",
                    "message": format!("The JSON body has a syntax error: {}", err)
                }
            });
            (StatusCode::BAD_REQUEST, Json(error)).into_response()
        }
        Err(JsonRejection::JsonDataError(err)) => {
            let error = json!({
                "error": {
                    "code": "invalid_json_data",
                    "message": format!("The JSON body did not match the expected structure: {}", err)
                }
            });
            (StatusCode::UNPROCESSABLE_ENTITY, Json(error)).into_response()
        }
        Err(JsonRejection::BytesRejection(err)) => {
            let error = json!({
                "error": {
                    "code": "body_read_failed",
                    "message": "The server could not read the complete request body"
                }
            });
            (err.status(), Json(error)).into_response()
        }
        Err(_) => {
            let error = json!({
                "error": {
                    "code": "unknown_json_error",
                    "message": "An unexpected error occurred while reading the JSON body"
                }
            });
            (StatusCode::BAD_REQUEST, Json(error)).into_response()
        }
    }
}
let app = Router::new().route("/users", post(create_user));

The MissingJsonContentType arm returns a structured JSON error. Instead of Axum's plain text message, the client receives a JSON object with a code field and a message field. This is much easier for a frontend application or another service to parse and display to a user.

Notice that the successful branch returns StatusCode::CREATED with a JSON body, while each failure branch returns a specific status code. The into_response() method converts the tuple of (StatusCode, Json<...>) into the Response type that the handler requires.

Handling JSON syntax errors

A JSON syntax error happens when the body is not valid JSON at all. This could be a missing closing brace, a trailing comma, a string without closing quotes, or any other violation of the JSON grammar.

When a client sends:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "secret",}'

The trailing comma after "secret" makes the JSON invalid. Axum catches this during parsing and creates a JsonRejection::JsonSyntaxError. The rejection's error message includes the position where parsing failed, for example Failed to parse the request body as JSON: trailing comma at line 1 column 58. Note that the rejection struct itself has no line() or column() methods; the position is part of the error text.

You can include that message in a debugging-friendly response.

Err(JsonRejection::JsonSyntaxError(err)) => {
    let error = json!({
        "error": {
            "code": "invalid_json_syntax",
            "message": format!("The request body contains invalid JSON syntax: {err}")
        }
    });
    (StatusCode::BAD_REQUEST, Json(error)).into_response()
}

Now the client gets back not just a generic failure, but the exact line and column where their JSON parser tripped. For a developer working with a command-line tool or a JavaScript client, this is the difference between an afternoon of debugging and a five-second fix.

Handling data errors from type mismatches

A JsonDataError happens when the JSON is perfectly valid, but the fields do not line up with the Rust struct you defined. This is different from a syntax error because the parser succeeds in reading the JSON, but the deserializer fails when it tries to create your typed struct.

Common causes include:

  • A field is missing from the JSON but is required in the struct.
  • A field has the wrong type (a number where a string is expected).
  • A field name is misspelled and does not match the struct field name.
  • Extra fields are present and the struct uses #[serde(deny_unknown_fields)]. By default serde ignores unknown fields, so extra fields alone do not cause an error.

Consider this request body:

{"email": "alice@example.com", "password": 12345}

The password field is a String in the struct, but the client sent a number. The JSON syntax is valid, so the parser succeeds, but deserialization into CreateUser fails with a JsonDataError.

The wrapped serde_path_to_error::Error<serde_json::Error> tells you the path to the field that caused the problem, but you need to enable the serde_path_to_error crate to get that path information easily.

What serdepathto_error does:

By default, serde_json errors do not include the full path of the failing field. The serde_path_to_error crate wraps the deserializer and tracks the path as it moves through the JSON. When an error occurs, you can retrieve a path like $.password instead of just a generic message. This crate is separate from Axum, but the Axum documentation demonstrates how to use it to improve rejection messages.

To use the path information, add serde_path_to_error to your Cargo.toml.

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

Then you can write a helper function that safely extracts the path from the error chain.

use std::error::Error;
fn find_error_source<'a, T>(err: &'a (dyn Error + 'static)) -> Option<&'a T>
where
    T: Error + 'static,
{
    if let Some(err) = err.downcast_ref::<T>() {
        Some(err)
    } else if let Some(source) = err.source() {
        find_error_source(source)
    } else {
        None
    }
}
fn serde_json_error_response<E>(err: E) -> (StatusCode, axum::Json<serde_json::Value>)
where
    E: Error + 'static,
{
    if let Some(err) = find_error_source::<serde_path_to_error::Error<serde_json::Error>>(&err) {
        let serde_json_err = err.inner();
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            axum::Json(serde_json::json!({
                "error": {
                    "code": "invalid_json_data",
                    "path": err.path().to_string(),
                    "line": serde_json_err.line(),
                    "column": serde_json_err.column(),
                }
            })),
        )
    } else {
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            axum::Json(serde_json::json!({
                "error": {
                    "code": "invalid_json_data",
                    "message": "Unknown deserialization error",
                }
            })),
        )
    }
}

This follows the pattern shown in the Axum documentation. It walks down the chain of wrapped errors to find the specific serde_path_to_error::Error type. If it finds one, it extracts the path, the line, and the column. The path is a string like .password or $.email, which points directly at the field the deserializer was trying to process when it failed. The helper returns 422 Unprocessable Entity for a data error, matching the status used for JsonDataError everywhere else on this page.

You would then call this helper from your handler's JsonDataError arm.

Err(JsonRejection::JsonDataError(err)) => {
    let (status, body) = serde_json_error_response(err);
    (status, body).into_response()
}

This relies on Axum internals:

The find_error_source pattern digs into the chain of error types that Axum currently uses. Axum does not guarantee that the internal error types will remain the same forever, even in non-major releases. This approach gives you excellent debugging information today, but you should treat it as a diagnostic tool rather than a stable public API. The safer, long-term approach is to validate your JSON before relying on these internal details, or to keep this extraction code isolated in a single helper function so it is easy to update if Axum changes its internals.

Handling body buffering failures

A BytesRejection is different from the other three variants because it does not usually mean the client sent bad JSON. It means the server failed to read the request body from the network, or it failed to buffer the bytes into memory before parsing.

This can happen if the client disconnects in the middle of sending the body, if the connection times out, or if the body exceeds the configured size limit. Those two cases deserve different statuses: an over-limit body is the client's fault and gets a 413 Payload Too Large, while a network failure is a server-side problem and gets a 500 Internal Server Error. The rejection itself knows which one it is, so use its status() method instead of hardcoding one status for both:

Err(JsonRejection::BytesRejection(err)) => {
    let error = json!({
        "error": {
            "code": "body_read_failed",
            "message": "The server could not read the complete request body"
        }
    });
    (err.status(), Json(error)).into_response()
}

In a production application, you would also log this rejection at the error level, because it indicates an infrastructure problem that might need attention.

The catch-all rejection arm

You might have noticed the Err(_) arm at the end of the match expression in the complete example. This arm is required because JsonRejection is marked as non-exhaustive in Axum. That means Axum reserves the right to add new variants in the future without it being considered a breaking change.

If you write a match that only covers the four main variants and Axum adds a fifth variant, your code will stop compiling when you upgrade Axum. The wildcard Err(_) arm guarantees that your handler always has a fallback for unknown rejection types.

Err(_) => {
    let error = json!({
        "error": {
            "code": "unknown_json_error",
            "message": "An unexpected error occurred while reading the JSON body"
        }
    });
    (StatusCode::BAD_REQUEST, Json(error)).into_response()
}

Treat this arm as your safety net. It does not need to be highly specific, but it should always return a sensible error response rather than panic.

A complete example with custom error handling

Here is the full handler from the earlier sections combined into one place, with all imports included, so you can see how everything fits together.

use axum::{
    extract::Json,
    extract::rejection::JsonRejection,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
use serde_json::json;
use std::error::Error;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}
fn find_error_source<'a, T>(err: &'a (dyn Error + 'static)) -> Option<&'a T>
where
    T: Error + 'static,
{
    if let Some(err) = err.downcast_ref::<T>() {
        Some(err)
    } else if let Some(source) = err.source() {
        find_error_source(source)
    } else {
        None
    }
}
fn serde_json_error_response<E>(err: E) -> (StatusCode, axum::Json<serde_json::Value>)
where
    E: Error + 'static,
{
    if let Some(err) = find_error_source::<serde_path_to_error::Error<serde_json::Error>>(&err) {
        let serde_json_err = err.inner();
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            axum::Json(serde_json::json!({
                "error": {
                    "code": "invalid_json_data",
                    "path": err.path().to_string(),
                    "line": serde_json_err.line(),
                    "column": serde_json_err.column(),
                }
            })),
        )
    } else {
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            axum::Json(serde_json::json!({
                "error": {
                    "code": "invalid_json_data",
                    "message": "Unknown deserialization error",
                }
            })),
        )
    }
}
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) -> Response {
    match payload {
        Ok(Json(user)) => {
            println!("Creating user with email: {}", user.email);
            (
                StatusCode::CREATED,
                Json(json!({ "status": "created", "email": user.email })),
            )
                .into_response()
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            let error = json!({
                "error": {
                    "code": "missing_content_type",
                    "message": "This endpoint requires the header: Content-Type: application/json"
                }
            });
            (StatusCode::UNSUPPORTED_MEDIA_TYPE, Json(error)).into_response()
        }
        Err(JsonRejection::JsonSyntaxError(err)) => {
            let error = json!({
                "error": {
                    "code": "invalid_json_syntax",
                    "message": format!("The request body contains invalid JSON syntax: {err}")
                }
            });
            (StatusCode::BAD_REQUEST, Json(error)).into_response()
        }
        Err(JsonRejection::JsonDataError(err)) => {
            let (status, body) = serde_json_error_response(err);
            (status, body).into_response()
        }
        Err(JsonRejection::BytesRejection(err)) => {
            let error = json!({
                "error": {
                    "code": "body_read_failed",
                    "message": "The server could not read the complete request body"
                }
            });
            (err.status(), Json(error)).into_response()
        }
        Err(_) => {
            let error = json!({
                "error": {
                    "code": "unknown_json_error",
                    "message": "An unexpected error occurred while reading the JSON body"
                }
            });
            (StatusCode::BAD_REQUEST, Json(error)).into_response()
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Server running on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

You can test this endpoint with different curl commands to see each rejection variant in action.

# Success
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "secret"}'
# Missing Content-Type
curl -X POST http://localhost:3000/users \
  -d '{"email": "alice@example.com", "password": "secret"}'
# Syntax error
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": }'
# Data error
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email": 42, "password": "secret"}'

Each response body is a structured JSON object that a client application can parse and display in a user-friendly way.

You now control the error path:

If you run these commands and see your custom JSON error responses come back with the correct status codes, you have successfully taken over the rejection handling from Axum. This is the foundation for building robust, user-friendly APIs that do not leak internal error details or confuse clients with plain text messages when JSON is expected.

Common mistakes and how to avoid them

The most frequent mistake when learning about JsonRejection is forgetting that the Content-Type header is required. If you test your endpoint with curl and omit -H "Content-Type: application/json", Axum rejects the request before your handler runs. You will see a 415 error and assume your code is broken, when the actual issue is the missing header in your test command.

Another mistake is thinking that wrapping the extractor in Result is optional. If you want Axum to return its default rejection response, use Json<T> directly. If you want your handler to handle the failure, you must use Result<Json<T>, JsonRejection>. There is no middle ground where Axum calls your handler and also returns its own error.

A subtle point that catches many beginners is that the handler must return a type that implements IntoResponse. In the examples above, the handler returns Response, which is the most flexible return type. If you return impl IntoResponse instead, every match arm must return the same concrete type. Using Response avoids this restriction and lets you return different tuple types for success and error cases.

Finally, remember that the request body can only be read once. If you try to use the String body extractor and the Json extractor together, Axum will refuse to compile because both extractors need to consume the body. When you are debugging a JSON rejection and want to see the raw body, use String or Bytes as the extractor instead of Json. That way you can log the body before attempting to parse it manually with serde_json::from_str.

Summary

The main insight from this page is that Axum's automatic JSON rejection behavior is a convenient default, but it is not a dead end. By understanding the JsonRejection enum and wrapping your extractor in Result, you move the error handling from Axum's internal response generator into your own handler. From there, you can return structured JSON errors, inspect the exact line and column of a syntax problem, extract the path of a data mismatch, and log infrastructure failures separately.

A good rule of thumb is to start with the plain Json<T> extractor when you are prototyping and happy with Axum's default rejection responses. As soon as you need to return a consistent JSON error shape, hide internal error details, or send specific status codes for different failure modes, switch to Result<Json<T>, JsonRejection>. The extra match arms are a small price to pay for full control over what your API says when a client sends something it should not have sent.