expression

Axum: convert Tower timeout errors

Tower timeout reports a service error, while Axum routes need a response. Convert the error outside the timeout layer and distinguish the elapsed error from unexpected failures. The 503 mapping is an example of a local service deadline policy. In-memory standalone Cargo example. Expected stdout (not executed): 503 Common mistake: Placing error conversion inside the layer that generates the error.

Formal Syntax & Structure

rust syntaxrust
ServiceBuilder::new().layer(HandleErrorLayer::new(handler)).timeout(duration)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread", start_paused = true)]async fn main() {    use axum::{routing::get, error_handling::HandleErrorLayer};    use tower::{BoxError, ServiceBuilder};    use std::time::Duration;    async fn map(err: BoxError) -> StatusCode {        if err.is::<tower::timeout::error::Elapsed>() { StatusCode::SERVICE_UNAVAILABLE }        else { StatusCode::INTERNAL_SERVER_ERROR }    }    let app = Router::new().route("/", get(|| async {        tokio::time::sleep(Duration::from_secs(10)).await;        "late"    })).layer(ServiceBuilder::new().layer(HandleErrorLayer::new(map)).timeout(Duration::from_secs(1)));    let r = app.oneshot(Request::new(Body::empty())).await.unwrap();    println!("{}", r.status().as_u16());}
Rust Reference