Skip to main content

Crate axum_problem

Crate axum_problem 

Source
Expand description

RFC 9457 problem details for axum.

§Quick start

use axum::{Router, routing::get, extract::Path};
use axum_problem::{AxumProblem, Problem, ProblemLayer};
use thiserror::Error;

#[derive(Debug, Error, AxumProblem)]
pub enum ApiError {
    #[error("order {id} not found")]
    #[problem(status = 404)]
    NotFound { id: i64 },

    #[error("unauthorized")]
    #[problem(status = 401)]
    Unauthorized,

    #[error("database error: {0}")]
    #[problem(status = 500, mask)]             // logs at error level (default)
    Database(String),

    #[error("rate limited: {0}")]
    #[problem(status = 429, mask, log = "warn")]  // logs at warn level
    RateLimited(String),
}

async fn get_order(Path(id): Path<i64>) -> Result<String, ApiError> {
    Err(ApiError::NotFound { id })
}

// Apply ProblemLayer to catch axum's own extractor errors
// (bad JSON body, wrong content-type, etc.) and convert them to RFC 9457.
let app: Router = Router::new()
    .route("/orders/:id", get(get_order))
    .layer(ProblemLayer);

The mask attribute hides the error detail from the HTTP response (preventing internal details leaking to clients) and logs the full error via tracing::error!.

§ProblemLayer

ProblemLayer is a Tower middleware that ensures every error response from your API uses application/problem+json. It intercepts any 4xx/5xx response that isn’t already a problem response and wraps it:

use axum::Router;
use axum_problem::ProblemLayer;

let app: Router = Router::new()
    /* ... routes ... */
    .layer(ProblemLayer);

Responses already in application/problem+json format pass through unchanged.

Structs§

Problem
An RFC 9457 problem details response.
ProblemLayer
Tower middleware layer that converts non-problem error responses to RFC 9457.
ProblemService
Tower service produced by ProblemLayer.

Functions§

status_title
Returns a short title for common HTTP status codes.

Derive Macros§

AxumProblem
Derive IntoResponse for an error enum, mapping each variant to an RFC 9457 problem details response.