Wrap InvalidMimeTypeException in HttpMediaTypeNotAcceptableException

The fix for #31254 resulted in an InvalidMimeTypeException being thrown
by MimeTypeUtils.sortBySpecificity() instead of an
IllegalArgumentException. However, InvalidMimeTypeException extends
IllegalArgumentException. Consequently, the change from
IllegalArgumentException to InvalidMimeTypeException did not result in
the desired effect in HeaderContentNegotiationStrategy.

HeaderContentNegotiationStrategy.resolveMediaTypes() still allows the
InvalidMimeTypeException to propagate as-is without wrapping it in an
HttpMediaTypeNotAcceptableException.

To address this issue, this commit catches InvalidMediaTypeException
and InvalidMimeTypeException in HeaderContentNegotiationStrategy and
wraps the exception in an HttpMediaTypeNotAcceptableException.

See gh-31254
See gh-31769
Closes gh-32483
This commit is contained in:
Sam Brannen
2024-03-19 14:20:40 +01:00
parent 836a0b3a40
commit ef02f0bad8
2 changed files with 25 additions and 2 deletions

View File

@@ -34,6 +34,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sam Brannen
*/
class HeaderContentNegotiationStrategyTests {
@@ -63,6 +64,27 @@ class HeaderContentNegotiationStrategyTests {
.containsExactly("text/html", "text/x-c", "text/x-dvi;q=0.8", "text/plain;q=0.5");
}
@Test // gh-32483
void resolveMediaTypesWithMaxElements() throws Exception {
String acceptHeaderValue = "text/plain, text/html,".repeat(25);
this.servletRequest.addHeader("Accept", acceptHeaderValue);
List<MediaType> mediaTypes = this.strategy.resolveMediaTypes(this.webRequest);
assertThat(mediaTypes).hasSize(50);
assertThat(mediaTypes.stream().map(Object::toString).distinct())
.containsExactly("text/plain", "text/html");
}
@Test // gh-32483
void resolveMediaTypesWithTooManyElements() {
String acceptHeaderValue = "text/plain,".repeat(51);
this.servletRequest.addHeader("Accept", acceptHeaderValue);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class)
.isThrownBy(() -> this.strategy.resolveMediaTypes(this.webRequest))
.withMessageStartingWith("Could not parse 'Accept' header")
.withMessageEndingWith("Too many elements");
}
@Test
void resolveMediaTypesParseError() {
this.servletRequest.addHeader("Accept", "textplain; q=0.5");