expression
Axum: typed success and error branches
A Result can express application outcomes when both branches can become HTTP responses. The handler returns a normal response for a known ID and a fixed public message for unknown IDs; no internal details are exposed. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 200 sample 404 item missing Common mistake: Returning a Rust error type that cannot convert into a response, or sending internal debugging data to clients.
Formal Syntax & Structure
rust syntaxrust
Result<String, (StatusCode, &'static str)>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::{extract::Path, routing::get}; async fn item(Path(id): Path<u32>) -> Result<String, (StatusCode, &'static str)> { if id == 1 { Ok("sample".into()) } else { Err((StatusCode::NOT_FOUND, "item missing")) } } let app = Router::new().route("/items/{id}", get(item)); for uri in ["/items/1", "/items/2"] { let r = app.clone().oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap(); println!("{} {}", r.status().as_u16(), std::str::from_utf8(&to_bytes(r.into_body(), 64).await.unwrap()).unwrap()); }}