mirror of
https://github.com/tokio-rs/axum.git
synced 2026-09-08 00:00:24 +02:00
examples(error-handling): Using thiserror for derive_from_request
This commit is contained in:
@@ -2,6 +2,7 @@ use axum::{extract::rejection::JsonRejection, http::StatusCode, response::IntoRe
|
|||||||
use axum_macros::FromRequest;
|
use axum_macros::FromRequest;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
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));
|
||||||
@@ -12,35 +13,27 @@ 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);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Error)]
|
||||||
pub struct ApiError {
|
pub enum ApiError {
|
||||||
code: StatusCode,
|
#[error(transparent)]
|
||||||
message: String,
|
JsonExtractorRejection(#[from] JsonRejection),
|
||||||
}
|
|
||||||
|
|
||||||
impl From<JsonRejection> for ApiError {
|
|
||||||
fn from(rejection: JsonRejection) -> Self {
|
|
||||||
let code = match rejection {
|
|
||||||
JsonRejection::JsonDataError(_) | JsonRejection::MissingJsonContentType(_) => {
|
|
||||||
StatusCode::BAD_REQUEST
|
|
||||||
}
|
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
};
|
|
||||||
Self {
|
|
||||||
code,
|
|
||||||
message: rejection.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for ApiError {
|
impl IntoResponse for ApiError {
|
||||||
fn into_response(self) -> axum::response::Response {
|
fn into_response(self) -> axum::response::Response {
|
||||||
let payload = json!({
|
let payload = json!({
|
||||||
"message": self.message,
|
"message": self.to_string(),
|
||||||
"timestamp": Utc::now(),
|
"timestamp": Utc::now(),
|
||||||
"origin": "derive_from_request"
|
"origin": "with_rejection"
|
||||||
});
|
});
|
||||||
|
let code = match self {
|
||||||
(self.code, axum::Json(payload)).into_response()
|
ApiError::JsonExtractorRejection(x) => match x {
|
||||||
|
JsonRejection::JsonDataError(_) | JsonRejection::MissingJsonContentType(_) => {
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
}
|
||||||
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
(code, axum::Json(payload)).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user