expression
Axum: map extraction errors to a public message
Accept the extractor result explicitly when the endpoint needs its own stable error representation. Preserve the rejection status but use a fixed safe public message. More detailed diagnostics belong in reviewed private logs, not raw request responses. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 400 invalid request Common mistake: Changing every rejection to 500 or echoing detailed deserialization errors to clients.
Formal Syntax & Structure
rust syntaxrust
Result<Json<Input>, JsonRejection>Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::{Json, extract::rejection::JsonRejection, routing::post}; #[derive(serde::Deserialize)] struct Input { value: u32 } async fn handle(input: Result<Json<Input>, JsonRejection>) -> Result<String, (StatusCode, &'static str)> { match input { Ok(Json(v)) => Ok(v.value.to_string()), Err(e) => Err((e.status(), "invalid request")) } } let app = Router::new().route("/value", post(handle)); let r = app.oneshot(Request::builder().method("POST").uri("/value").header("content-type", "application/json").body(Body::from("{" )).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 64).await.unwrap()).unwrap());}