Skip to content

HeaderContentNegotiationStrategy.resolveMediaTypes throws unexpected IllegalArgumentException  #31254

Closed
@mhankus

Description

@mhankus

Affects: 6.0.11

Parsing of http accept header throws IllegalArguemntException which is unexpected, and causes unexpected application behavior.
Example stack trace

Too many elements
java.lang.IllegalArgumentException: Too many elements
at org.springframework.util.Assert.isTrue(Assert.java:122)
at org.springframework.util.MimeTypeUtils.sortBySpecificity(MimeTypeUtils.java:365)
at org.springframework.web.accept.HeaderContentNegotiationStrategy.resolveMediaTypes(HeaderContentNegotiationStrategy.java:55)
at org.springframework.web.accept.ContentNegotiationManager.resolveMediaTypes(ContentNegotiationManager.java:128)
at org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.getAcceptedMediaTypes(ProducesRequestCondition.java:290)
at org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.getMatchingCondition(ProducesRequestCondition.java:208)
at org.springframework.web.servlet.mvc.method.RequestMappingInfo.getMatchingCondition(RequestMappingInfo.java:401)
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getMatchingMapping(RequestMappingInfoHandlerMapping.java:110)
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getMatchingMapping(RequestMappingInfoHandlerMapping.java:68)

Class HeaderContentNegotiationStrategy currently catches only InvalidMediaTypeException, but IllegalArgumentException can also be thrown here.

public List<MediaType> resolveMediaTypes(NativeWebRequest request)
			throws HttpMediaTypeNotAcceptableException {

		String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT);
		if (headerValueArray == null) {
			return MEDIA_TYPE_ALL_LIST;
		}

		List<String> headerValues = Arrays.asList(headerValueArray);
		try {
			List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
			MimeTypeUtils.sortBySpecificity(mediaTypes);
			return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
		}
		catch (InvalidMediaTypeException ex) {
			throw new HttpMediaTypeNotAcceptableException(
					"Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
		}
	}

please consider changing of this catch to IllegalArgumentException (InvalidMediaTypeException is a subclass of IllegalArgumentException). This change would make behavior more predictable.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions