Expand description
Error handling layer for axum that supports extractors and async functions.
This crate provides HandleErrorLayer
which works similarly to
axum::error_handling::HandleErrorLayer
except that it supports
extractors and async functions:
use axum::{
Router,
BoxError,
response::IntoResponse,
http::{StatusCode, Method, Uri},
routing::get,
};
use tower::{ServiceBuilder, timeout::error::Elapsed};
use std::time::Duration;
use axum_handle_error_extract::HandleErrorLayer;
let app = Router::new()
.route("/", get(|| async {}))
.layer(
ServiceBuilder::new()
// timeouts produces errors, so we handle those with `handle_error`
.layer(HandleErrorLayer::new(handle_error))
.timeout(Duration::from_secs(10))
);
// our handler take can 0 to 16 extractors and the final argument must
// always be the error produced by the middleware
async fn handle_error(
method: Method,
uri: Uri,
error: BoxError,
) -> impl IntoResponse {
if error.is::<Elapsed>() {
(
StatusCode::REQUEST_TIMEOUT,
format!("{} {} took too long", method, uri),
)
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("{} {} failed: {}", method, uri, error),
)
}
}
Not running any extractors is also supported:
use axum::{
Router,
BoxError,
response::IntoResponse,
http::StatusCode,
routing::get,
};
use tower::{ServiceBuilder, timeout::error::Elapsed};
use std::time::Duration;
use axum_handle_error_extract::HandleErrorLayer;
let app = Router::new()
.route("/", get(|| async {}))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_error))
.timeout(Duration::from_secs(10))
);
// this function just takes the error
async fn handle_error(error: BoxError) -> impl IntoResponse {
if error.is::<Elapsed>() {
(
StatusCode::REQUEST_TIMEOUT,
"Request timeout".to_string(),
)
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
)
}
}
See axum::error_handling
for more details on axum’s error handling model and
axum::extract
for more details on extractors.
§The future
In axum 0.4 this will replace the current axum::error_handling::HandleErrorLayer
.
Structs§
- Handle
Error - A
Service
adapter that handles errors by converting them into responses. - Handle
Error Layer Layer
that appliesHandleError
which is aService
adapter that handles errors by converting them into responses.- Response
Future - Response future for
HandleError
.
Traits§
- Handle
Error Ext - Extension trait to
Service
for handling errors by mapping them to responses.