IssueType : Bug SpringBoot Version : 3.0.13 Problem Description:

Http request with invalid MediaTypes in Accept header returns 403 instead of 406 which is configured at ExceptionHandler. Getting below exception for unit test testInvalidAcceptHeadersWithoutJsonType()

2024-02-22T12:23:29.026+05:30  WARN 14240 --- [o-auto-1-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler com.example.TestRestAPI.controller.RESTApiAdviser#handleMyException(MyException)

org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:256) ~[spring-webmvc-6.0.14.jar:6.0.14]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:194) ~[spring-webmvc-6.0.14.jar:6.0.14]

While unit test testInvalidAcceptHeadersWithJsonType(), where we just gave an additional application/json MediaType in Accept header, it returns excepted 406.

Attaching the sample code with both the unit tests TestRestAPI.zip

Comment From: wilkinsona

Open source support for Spring Boot 3.0.x has ended. Please upgrade to Spring Boot 3.1.x or 3.2.x. If the problem still occurs, let us know and we can take another look.

Comment From: akanks75

Even after upgrading to spring Boot 3.1.8, issue still persist. Attaching code with updated version TestRestAPI.zip

Comment From: scottfrederick

@akanks75 This appears to be working as designed.

With both test cases in your sample, the @ExceptionHandler(MyException.class) is getting called and returning the ErrorInfo object with @ResponseBody. Returning an object from the exception handler with @ResponseBody implies that the response should be marshalled to JSON, but in the testInvalidAcceptHeadersWithoutJsonType case Spring Framework detects that APPLICATION_JSON is not an acceptable media type. This results in a HttpMediaTypeNotAcceptableException being thrown. To illustrate the point, both tests cases will work if the exception handler returns a String instead of an ErrorInfo, because TEXT_PLAIN is an acceptable media type in both cases.

Note that Spring Boot is not involved in this flow, as Spring Framework is doing all of the response handling.

If you have any further questions, please post them to StackOverflow.