From bbecfa29d509d211b16ea60307b27477f24e17e9 Mon Sep 17 00:00:00 2001 From: Jan Trefil <8711792+htrefil@users.noreply.github.com> Date: Mon, 10 Jun 2024 20:25:43 +0200 Subject: [PATCH] Add status methods to Form and Query rejections --- 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 8d2d30f91c..adad8ac675 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 7bd023cf06..11a128c3f5 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,