Attribute Macro axum::debug_handler

source · []
#[debug_handler]
Available on crate feature macros only.
Expand description

Generates better error messages when applied handler functions.

While using axum, you can get long error messages for simple mistakes. For example:

use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

fn handler() -> &'static str {
    "Hello, world"
}

You will get a long error message about function not implementing Handler trait. But why does this function not implement it? To figure it out, the debug_handler macro can be used.

#[debug_handler]
fn handler() -> &'static str {
    "Hello, world"
}
error: handlers must be async functions
  --> main.rs:xx:1
   |
xx | fn handler() -> &'static str {
   | ^^

As the error message says, handler function needs to be async.

use axum::{routing::get, Router};
use axum_macros::debug_handler;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

#[debug_handler]
async fn handler() -> &'static str {
    "Hello, world"
}

Changing request body type

By default #[debug_handler] assumes your request body type is axum::body::Body. This will work for most extractors but, for example, it wont work for Request<axum::body::BoxBody>, which only implements FromRequest<BoxBody> and not FromRequest<Body>.

To work around that the request body type can be customized like so:

use axum::{body::BoxBody, http::Request};

#[debug_handler(body = BoxBody)]
async fn handler(request: Request<BoxBody>) {}

Performance

This macro has no effect when compiled with the release profile. (eg. cargo build --release)