From 573e74b8bd735bf0f120e4f5778d471f3d057a50 Mon Sep 17 00:00:00 2001 From: Russell Bolles Date: Thu, 13 Mar 2025 12:22:25 -0700 Subject: [PATCH] Refine FormHttpMessageConverter exception handling FormHttpMessageConverter could throw a more specific HttpMessageNotReadableException instead of an IllegalArgumentException when the http form data is invalid. See gh-34594 Signed-off-by: Russell Bolles --- .../converter/FormHttpMessageConverter.java | 18 +++++++--- .../FormHttpMessageConverterTests.java | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java index 34062542fa..7e72fad230 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java @@ -353,12 +353,22 @@ public class FormHttpMessageConverter implements HttpMessageConverter body = new LinkedMultiValueMap<>(); @@ -410,6 +432,17 @@ class FormHttpMessageConverterTests { assertThat(this.converter.canWrite(clazz, mediaType)).as(clazz.getSimpleName() + " : " + mediaType).isFalse(); } + private void assertInvalidFormIsRejectedWithSpecificException(String body) { + MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.ISO_8859_1)); + inputMessage.getHeaders().setContentType( + new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1)); + + assertThatThrownBy(() -> this.converter.read(null, inputMessage)) + .isInstanceOf(HttpMessageNotReadableException.class) + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasMessage("Could not decode HTTP form payload"); + } + private static class MockHttpOutputMessageRequestContext implements UploadContext {