Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion axum-extra/src/extract/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 10 additions & 1 deletion axum-extra/src/extract/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down