Skip to content
Myr

derive_from_request.rs

This file

Path

examples/customize-extractor-error/src/derive_from_request.rs

65 lines · 2.2 KiB · Rust

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than dcbcf5c point at it.

axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c

lines 1–65why, one step back
1//! Uses `axum::extract::FromRequest` to wrap another extractor and customize the
2//! rejection3//!4//! + Easy learning curve: Deriving `FromRequest` generates a `FromRequest`5//! implementation for your type using another extractor. You only need6//! to provide a `From` impl between the original rejection type and the7//! target rejection. Crates like [`thiserror`] can provide such conversion8//! using derive macros.9//! - Boilerplate: Requires deriving `FromRequest` for every custom rejection10//! - There are some known limitations: [FromRequest#known-limitations]11//!12//! [`thiserror`]: https://crates.io/crates/thiserror13//! [FromRequest#known-limitations]: https://docs.rs/axum-macros/*/axum_macros/derive.FromRequest.html#known-limitations14use axum::{15 extract::rejection::JsonRejection, extract::FromRequest, http::StatusCode,16 response::IntoResponse,17};18use serde::Serialize;19use serde_json::{json, Value};2021pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {22 Json(dbg!(value))23}2425// create an extractor that internally uses `axum::Json` but has a custom rejection26#[derive(FromRequest)]27#[from_request(via(axum::Json), rejection(ApiError))]28pub struct Json<T>(T);2930// We implement `IntoResponse` for our extractor so it can be used as a response31impl<T: Serialize> IntoResponse for Json<T> {32 fn into_response(self) -> axum::response::Response {33 let Self(value) = self;34 axum::Json(value).into_response()35 }36}3738// We create our own rejection type39#[derive(Debug)]40pub struct ApiError {41 status: StatusCode,42 message: String,43}4445// We implement `From<JsonRejection> for ApiError`46impl From<JsonRejection> for ApiError {47 fn from(rejection: JsonRejection) -> Self {48 Self {49 status: rejection.status(),50 message: rejection.body_text(),51 }52 }53}5455// We implement `IntoResponse` so `ApiError` can be used as a response56impl IntoResponse for ApiError {57 fn into_response(self) -> axum::response::Response {58 let payload = json!({59 "message": self.message,60 "origin": "derive_from_request"61 });6263 (self.status, axum::Json(payload)).into_response()64 }65}