expression
Axum: typed structured application errors
Define an application error type that maps domain failures to stable HTTP status and JSON fields. Clients can branch on the machine-readable code instead of parsing prose. Do not expose internal database messages or secrets in the response. In-memory standalone Cargo example. Expected stdout (not executed): 404 item_missing Common mistake: Returning raw internal error messages as the public API contract.
Formal Syntax & Structure
rust syntaxrust
impl IntoResponse for ApiErrorWorking 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, routing::get, response::{Response, IntoResponse}}; struct ApiError; impl IntoResponse for ApiError { fn into_response(self) -> Response { (StatusCode::NOT_FOUND, Json(serde_json::json!({"code":"item_missing"}))).into_response() } } async fn find() -> Result<&'static str, ApiError> { Err(ApiError) } let r = Router::new().route("/", get(find)).oneshot(Request::new(Body::empty())).await.unwrap(); println!("{}", r.status().as_u16()); let b = to_bytes(r.into_body(), 128).await.unwrap(); let v: serde_json::Value = serde_json::from_slice(&b).unwrap(); println!("{}", v["code"].as_str().unwrap());}