pub fn with_error_handler<Validator, ErrorHandler>(
validator: Validator,
error_handler: ErrorHandler,
) -> Layer<State<Validator, ErrorHandler>>
Expand description
Create a new HTTP request validating layer with custom error handling.
ยงExamples
use axum::{routing::get, Router, http::StatusCode};
use axum_request_validator::{Error, ErrorHandler};
#[derive(Debug, Clone)]
struct MyErrorHandler;
impl<V> ErrorHandler<V> for MyErrorHandler
where
V: std::fmt::Display + Send + Sync + 'static,
{
type Response = (StatusCode, String);
async fn handle_error(&self, error: Error<V>) -> Self::Response {
match error {
Error::BodyBuffering(error) => (
StatusCode::BAD_REQUEST,
format!("Unable to buffer the request: {error}"),
),
Error::Validation(error) => (
StatusCode::FORBIDDEN,
format!("Invalid request: {error}"),
),
}
}
}
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.route_layer(axum_request_validator::with_error_handler(MyValidator, MyErrorHandler));