mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-27 00:00:24 +02:00
Add IntoResponse impl to customize-extractor-error example (#2191)
This commit is contained in:
@@ -15,10 +15,11 @@ use axum::{
|
|||||||
extract::rejection::JsonRejection, extract::FromRequest, http::StatusCode,
|
extract::rejection::JsonRejection, extract::FromRequest, http::StatusCode,
|
||||||
response::IntoResponse,
|
response::IntoResponse,
|
||||||
};
|
};
|
||||||
|
use serde::Serialize;
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {
|
pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {
|
||||||
Json(dbg!(value));
|
Json(dbg!(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
// create an extractor that internally uses `axum::Json` but has a custom rejection
|
// create an extractor that internally uses `axum::Json` but has a custom rejection
|
||||||
@@ -26,6 +27,14 @@ pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {
|
|||||||
#[from_request(via(axum::Json), rejection(ApiError))]
|
#[from_request(via(axum::Json), rejection(ApiError))]
|
||||||
pub struct Json<T>(T);
|
pub struct Json<T>(T);
|
||||||
|
|
||||||
|
// We implement `IntoResponse` for our extractor so it can be used as a response
|
||||||
|
impl<T: Serialize> IntoResponse for Json<T> {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let Self(value) = self;
|
||||||
|
axum::Json(value).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// We create our own rejection type
|
// We create our own rejection type
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ApiError {
|
pub struct ApiError {
|
||||||
|
|||||||
Reference in New Issue
Block a user