with_rejection.rs
This file
Path
examples/customize-extractor-error/src/with_rejection.rs
57 lines · 2.1 KiB · Rust
Last changed by
chore: fix typos (#3758)David Pedersenbefore adoption5bc0046
History of this fileTake it
1//! Uses `axum_extra::extract::WithRejection` to transform one rejection into2//! another3//!4//! + Easy learning curve: `WithRejection` acts as a wrapper for another5//! already existing extractor. You only need to provide a `From` impl6//! between the original rejection type and the target rejection. Crates like7//! `thiserror` can provide such conversion using derive macros. See8//! [`thiserror`]9//! - Verbose types: types become much larger, which makes them difficult to10//! read. Current limitations on type aliasing make it impossible to destructure11//! a type alias. See [#1116]12//!13//! [`thiserror`]: https://crates.io/crates/thiserror14//! [#1116]: https://github.com/tokio-rs/axum/issues/1116#issuecomment-11861976841516use axum::{extract::rejection::JsonRejection, response::IntoResponse, Json};17use axum_extra::extract::WithRejection;18use serde_json::{json, Value};19use thiserror::Error;2021pub async fn handler(22 // `WithRejection` will extract `Json<Value>` from the request. If it fails,23 // `JsonRejection` will be transform into `ApiError` and returned as response24 // to the client.25 //26 // The second constructor argument is not meaningful and can be safely ignored27 WithRejection(Json(value), _): WithRejection<Json<Value>, ApiError>,28) -> impl IntoResponse {29 Json(dbg!(value))30}3132// We derive `thiserror::Error`33#[derive(Debug, Error)]34pub enum ApiError {35 // The `#[from]` attribute generates `From<JsonRejection> for ApiError`36 // implementation. See `thiserror` docs for more information37 #[error(transparent)]38 JsonExtractorRejection(#[from] JsonRejection),39}4041// We implement `IntoResponse` so ApiError can be used as a response42impl IntoResponse for ApiError {43 fn into_response(self) -> axum::response::Response {44 let (status, message) = match self {45 ApiError::JsonExtractorRejection(json_rejection) => {46 (json_rejection.status(), json_rejection.body_text())47 }48 };4950 let payload = json!({51 "message": message,52 "origin": "with_rejection"53 });5455 (status, Json(payload)).into_response()56 }57}