Allow querying of HTTP status codes for query and form rejections (#2781)

This commit is contained in:
htrefil 2024-12-26 12:21:24 +01:00 committed by GitHub
parent 12d7d9c03c
commit 0b06f0c54e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 2 deletions

View file

@ -77,13 +77,24 @@ pub enum FormRejection {
FailedToDeserializeForm(Error), 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 { impl IntoResponse for FormRejection {
fn into_response(self) -> Response { fn into_response(self) -> Response {
let status = self.status();
match self { match self {
Self::RawFormRejection(inner) => inner.into_response(), Self::RawFormRejection(inner) => inner.into_response(),
Self::FailedToDeserializeForm(inner) => { Self::FailedToDeserializeForm(inner) => {
let body = format!("Failed to deserialize form: {inner}"); let body = format!("Failed to deserialize form: {inner}");
let status = StatusCode::BAD_REQUEST;
axum_core::__log_rejection!( axum_core::__log_rejection!(
rejection_type = Self, rejection_type = Self,
body_text = body, body_text = body,

View file

@ -111,12 +111,21 @@ pub enum QueryRejection {
FailedToDeserializeQueryString(Error), 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 { impl IntoResponse for QueryRejection {
fn into_response(self) -> Response { fn into_response(self) -> Response {
let status = self.status();
match self { match self {
Self::FailedToDeserializeQueryString(inner) => { Self::FailedToDeserializeQueryString(inner) => {
let body = format!("Failed to deserialize query string: {inner}"); let body = format!("Failed to deserialize query string: {inner}");
let status = StatusCode::BAD_REQUEST;
axum_core::__log_rejection!( axum_core::__log_rejection!(
rejection_type = Self, rejection_type = Self,
body_text = body, body_text = body,