From 7699b4af9c11737391efde8465ae8cc80632ea87 Mon Sep 17 00:00:00 2001 From: Igor Murzich Date: Wed, 8 Oct 2025 17:39:58 +0300 Subject: [PATCH] =?UTF-8?q?Retain=20order=20of=20produces=20media=20types?= =?UTF-8?q?=20in=20@=E2=81=A0ExceptionHandler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes gh-35587 Signed-off-by: Igor Murzich --- .../method/annotation/ExceptionHandlerMethodResolver.java | 4 ++-- .../annotation/ExceptionHandlerMethodResolverTests.java | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java index 05698967e37..45e9470bc8f 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -121,7 +121,7 @@ public class ExceptionHandlerMethodResolver { if (exceptions.isEmpty()) { throw new IllegalStateException("No exception types mapped to " + method); } - Set mediaTypes = new HashSet<>(); + Set mediaTypes = new LinkedHashSet<>(); for (String mediaType : exceptionHandler.produces()) { try { mediaTypes.add(MediaType.parseMediaType(mediaType)); diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java index a99eb76ced0..aa9a9530160 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java @@ -117,6 +117,13 @@ class ExceptionHandlerMethodResolverTests { assertThat(resolver.resolveExceptionMapping(new IllegalArgumentException(), MediaType.TEXT_HTML).getHandlerMethod().getName()).isEqualTo("handleHtml"); } + @Test + void shouldKeepProduceMediaTypesOrder() { + ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(MediaTypeController.class); + assertThat(resolver.resolveExceptionMapping(new IllegalArgumentException(), MediaType.TEXT_HTML).getProducibleTypes().toString()).isEqualTo("[text/html, */*]"); + } + + @Test void shouldResolveMethodWithCompatibleMediaType() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(MediaTypeController.class);