expression

Axum: unmatched path fallback

A fallback handles requests for paths that do not match a registered route. It does not replace the default method-not-allowed response for a known path. Keep a custom fallback status accurate for clients. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 404 missing route 405 Common mistake: Returning 200 for a missing API route or expecting fallback to handle unsupported methods.

Formal Syntax & Structure

rust syntaxrust
Router::fallback(handler)

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::routing::get;    let app = Router::new().route("/known", get(|| async { "known" })).fallback(|| async { (StatusCode::NOT_FOUND, "missing route") });    for (method, uri) in [("GET", "/lost"), ("POST", "/known")] {        let r = app.clone().oneshot(Request::builder().method(method).uri(uri).body(Body::empty()).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());        if r.status() == StatusCode::NOT_FOUND { println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 64).await.unwrap()).unwrap()); }    }}
Rust Reference