custom_extractor.rs
This file
Path
examples/customize-extractor-error/src/custom_extractor.rs
59 lines · 2.1 KiB · Rust
Last changed by
Not known.
History of this fileTake it
1//! Manual implementation of `FromRequest` that wraps another extractor2//!3//! + Powerful API: Implementing `FromRequest` grants access to `RequestParts`4//! and `async/await`. This means that you can create more powerful rejections5//! - Boilerplate: Requires creating a new extractor for every custom rejection6//! - Complexity: Manually implementing `FromRequest` results on more complex code7use axum::{8 extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request},9 http::StatusCode,10 response::IntoResponse,11 RequestPartsExt,12};13use serde_json::{json, Value};1415pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {16 Json(dbg!(value));17}1819// We define our own `Json` extractor that customizes the error from `axum::Json`20pub struct Json<T>(pub T);2122impl<S, T> FromRequest<S> for Json<T>23where24 axum::Json<T>: FromRequest<S, Rejection = JsonRejection>,25 S: Send + Sync,26{27 type Rejection = (StatusCode, axum::Json<Value>);2829 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {30 let (mut parts, body) = req.into_parts();3132 // We can use other extractors to provide better rejection messages.33 // For example, here we are using `axum::extract::MatchedPath` to34 // provide a better error message.35 //36 // Have to run that first since `Json` extraction consumes the request.37 let path = parts38 .extract::<MatchedPath>()39 .await40 .map(|path| path.as_str().to_owned())41 .ok();4243 let req = Request::from_parts(parts, body);4445 match axum::Json::<T>::from_request(req, state).await {46 Ok(value) => Ok(Self(value.0)),47 // convert the error from `axum::Json` into whatever we want48 Err(rejection) => {49 let payload = json!({50 "message": rejection.body_text(),51 "origin": "custom_extractor",52 "path": path,53 });5455 Err((rejection.status(), axum::Json(payload)))56 }57 }58 }59}