From 6f7ff8556587d51c6919a864926e4b8090f92c3f Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Sun, 16 Jul 2023 01:40:31 +0200 Subject: [PATCH] Fix example for accessing inner extrator errors (#2095) --- axum/src/docs/extract.md | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/axum/src/docs/extract.md b/axum/src/docs/extract.md index bba8a0733a..763fd9b0a4 100644 --- a/axum/src/docs/extract.md +++ b/axum/src/docs/extract.md @@ -348,13 +348,16 @@ async fn handler( } } -// attempt to extract the inner `serde_json::Error`, if that succeeds we can -// provide a more specific error +// attempt to extract the inner `serde_path_to_error::Error`, +// if that succeeds we can provide a more specific error. +// +// `Json` uses `serde_path_to_error` so the error will be wrapped in `serde_path_to_error::Error`. fn serde_json_error_response(err: E) -> (StatusCode, String) where E: Error + 'static, { - if let Some(serde_json_err) = find_error_source::(&err) { + if let Some(err) = find_error_source::>(&err) { + let serde_json_err = err.inner(); ( StatusCode::BAD_REQUEST, format!( @@ -382,6 +385,24 @@ where None } } +# +# #[tokio::main] +# async fn main() { +# use axum::extract::FromRequest; +# +# let req = axum::http::Request::builder() +# .header("content-type", "application/json") +# .body(axum::body::Body::from("{")) +# .unwrap(); +# +# let err = match Json::::from_request(req, &()).await.unwrap_err() { +# JsonRejection::JsonSyntaxError(err) => err, +# _ => panic!(), +# }; +# +# let (_, body) = serde_json_error_response(err); +# assert_eq!(body, "Invalid JSON at line 1 column 1"); +# } ``` Note that while this approach works it might break in the future if axum changes