fix: Return specific error message when multipart body limit is exceeded (#3611)

This commit is contained in:
Andrea Bozzo
2026-03-25 10:49:23 +01:00
committed by Yann Simon
parent 83cd0c6ff9
commit 47fef02bad
2 changed files with 44 additions and 2 deletions
+22 -1
View File
@@ -247,7 +247,11 @@ impl MultipartError {
/// Get the response body text used for this rejection.
pub fn body_text(&self) -> String {
let body = self.source.to_string();
let body = if is_body_limit_error(&self.source) {
"Request payload is too large".to_owned()
} else {
self.source.to_string()
};
axum_core::__log_rejection!(
rejection_type = Self,
body_text = body,
@@ -298,6 +302,22 @@ fn status_code_from_multer_error(err: &multer::Error) -> StatusCode {
}
}
fn is_body_limit_error(err: &multer::Error) -> bool {
match err {
multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => true,
multer::Error::StreamReadFailed(err) => {
if let Some(err) = err.downcast_ref::<multer::Error>() {
return is_body_limit_error(err);
}
err.downcast_ref::<axum_core::Error>()
.and_then(|err| err.source())
.and_then(|err| err.downcast_ref::<http_body_util::LengthLimitError>())
.is_some()
}
_ => false,
}
}
impl IntoResponse for MultipartError {
fn into_response(self) -> Response {
(self.status(), self.body_text()).into_response()
@@ -403,6 +423,7 @@ mod tests {
let res = client.post("/").multipart(form).await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(res.text().await, "Request payload is too large");
}
#[tokio::test]
+22 -1
View File
@@ -244,7 +244,11 @@ impl MultipartError {
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
self.source.to_string()
if is_body_limit_error(&self.source) {
"Request payload is too large".to_owned()
} else {
self.source.to_string()
}
}
/// Get the status code used for this rejection.
@@ -289,6 +293,22 @@ fn status_code_from_multer_error(err: &multer::Error) -> StatusCode {
}
}
fn is_body_limit_error(err: &multer::Error) -> bool {
match err {
multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => true,
multer::Error::StreamReadFailed(err) => {
if let Some(err) = err.downcast_ref::<multer::Error>() {
return is_body_limit_error(err);
}
err.downcast_ref::<crate::Error>()
.and_then(|err| err.source())
.and_then(|err| err.downcast_ref::<http_body_util::LengthLimitError>())
.is_some()
}
_ => false,
}
}
impl fmt::Display for MultipartError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Error parsing `multipart/form-data` request")
@@ -407,6 +427,7 @@ mod tests {
let res = client.post("/").multipart(form).await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(res.text().await, "Request payload is too large");
}
#[crate::test]