From 0b06f0c54ef659ce1f23be137a5c719d1697495c Mon Sep 17 00:00:00 2001 From: htrefil <8711792+htrefil@users.noreply.github.com> Date: Thu, 26 Dec 2024 12:21:24 +0100 Subject: [PATCH] Allow querying of HTTP status codes for query and form rejections (#2781) --- axum-extra/src/extract/form.rs | 13 ++++++++++++- axum-extra/src/extract/query.rs | 11 ++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/axum-extra/src/extract/form.rs b/axum-extra/src/extract/form.rs index 8d2d30f9..adad8ac6 100644 --- a/axum-extra/src/extract/form.rs +++ b/axum-extra/src/extract/form.rs @@ -77,13 +77,24 @@ pub enum FormRejection { FailedToDeserializeForm(Error), } +impl FormRejection { + /// Get the status code used for this rejection. + pub fn status(&self) -> StatusCode { + // Make sure to keep this in sync with `IntoResponse` impl. + match self { + Self::RawFormRejection(inner) => inner.status(), + Self::FailedToDeserializeForm(_) => StatusCode::BAD_REQUEST, + } + } +} + impl IntoResponse for FormRejection { fn into_response(self) -> Response { + let status = self.status(); match self { Self::RawFormRejection(inner) => inner.into_response(), Self::FailedToDeserializeForm(inner) => { let body = format!("Failed to deserialize form: {inner}"); - let status = StatusCode::BAD_REQUEST; axum_core::__log_rejection!( rejection_type = Self, body_text = body, diff --git a/axum-extra/src/extract/query.rs b/axum-extra/src/extract/query.rs index 7bd023cf..11a128c3 100644 --- a/axum-extra/src/extract/query.rs +++ b/axum-extra/src/extract/query.rs @@ -111,12 +111,21 @@ pub enum QueryRejection { FailedToDeserializeQueryString(Error), } +impl QueryRejection { + /// Get the status code used for this rejection. + pub fn status(&self) -> StatusCode { + match self { + Self::FailedToDeserializeQueryString(_) => StatusCode::BAD_REQUEST, + } + } +} + impl IntoResponse for QueryRejection { fn into_response(self) -> Response { + let status = self.status(); match self { Self::FailedToDeserializeQueryString(inner) => { let body = format!("Failed to deserialize query string: {inner}"); - let status = StatusCode::BAD_REQUEST; axum_core::__log_rejection!( rejection_type = Self, body_text = body,