1Add a fallback [`Handler`] to the router.
2
3This service will be called if no routes matches the incoming request.
4
5```rust
6use axum::{
7    Router,
8    routing::get,
9    handler::Handler,
10    response::IntoResponse,
11    http::{StatusCode, Uri},
12};
13
14let app = Router::new()
15    .route("/foo", get(|| async { /* ... */ }))
16    .fallback(fallback);
17
18async fn fallback(uri: Uri) -> (StatusCode, String) {
19    (StatusCode::NOT_FOUND, format!("No route for {}", uri))
20}
21# async {
22# hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
23# };
24```
25
26Fallbacks only apply to routes that aren't matched by anything in the
27router. If a handler is matched by a request but returns 404 the
28fallback is not called.
29
30# Handling all requests without other routes
31
32Using `Router::new().fallback(...)` to accept all request regardless of path or
33method, if you don't have other routes, isn't optimal:
34
35```rust
36use axum::Router;
37
38async fn handler() {}
39
40let app = Router::new().fallback(handler);
41
42# async {
43axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
44    .serve(app.into_make_service())
45    .await
46    .unwrap();
47# };
48```
49
50Running the handler directly is faster since it avoids the overhead of routing:
51
52```rust
53use axum::handler::HandlerWithoutStateExt;
54
55async fn handler() {}
56
57# async {
58axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
59    .serve(handler.into_make_service())
60    .await
61    .unwrap();
62# };
63```
64