Answer#
Axum can turn any Result<T, E> into a response when both T and E implement IntoResponse. So give your errors that trait once, and every handler can use ?.
use axum::{
body::{to_bytes, Body},
extract::Path,
http::{Request, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
};
use tower::ServiceExt;
#[derive(Debug, thiserror::Error)]
enum AppError {
#[error("not found")]
NotFound,
#[error("bad input: {0}")]
BadInput(#[from] std::num::ParseIntError),
#[error("database failure: {0}")]
Database(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
AppError::BadInput(e) => (StatusCode::BAD_REQUEST, e.to_string()),
AppError::Database(_) => {
eprintln!("log only: {self}"); // the detail goes to the log, not to the client
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string())
}
};
(status, message).into_response()
}
}
async fn show(Path(raw): Path<String>) -> Result<String, AppError> {
let id: u32 = raw.parse()?; // ParseIntError -> AppError::BadInput through #[from]
match id {
0 => Err(AppError::Database("connection refused: 10.0.0.5:5432".into())),
1 => Ok("user 1".into()),
_ => Err(AppError::NotFound),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{id}", get(show));
for uri in ["/users/1", "/users/9", "/users/x1", "/users/0"] {
let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{uri} -> {status} {}", String::from_utf8_lossy(&body));
}
}/users/1 -> 200 user 1
/users/9 -> 404 not found
/users/x1 -> 400 invalid digit found in string
log only: database failure: connection refused: 10.0.0.5:5432
/users/0 -> 500 internal error#[from]onParseIntErrorletsraw.parse()?convert the error intoAppError::BadInputwithout amap_err.- The database error carries the server address (
10.0.0.5:5432) in its text. The client got onlyinternal error; the detail went to the log line printed byeprintln!(usetracing::error!in a real server). - Each variant picks its own status: 404, 400, 500.
thiserror = "2.0.21"Common mistakes#
- Sending
error.to_string()of an internal error to the client. It can reveal hosts, file paths and SQL. - One
Stringas the error type for everything: the status then cannot depend on the kind of error.
Related questions#
Should the body be text or JSON?#
For an API, JSON in one fixed shape is easier for clients. The (status, Json(...)) tuple works the same way as the (status, String) used here.
What about panics?#
A panic is not an error value. See the thread on catching panics in a handler.
Sources#
- axum,
IntoResponse: https://docs.rs/axum/0.8.9/axum/response/trait.IntoResponse.html (read 2026-12-05) - axum, error handling: https://docs.rs/axum/0.8.9/axum/error_handling/index.html (read 2026-12-05)