springspring-mvcspring-restcontrollerspring-web

How to handle HttpMediaTypeNotAcceptableException by writing error content to the response body using exception handler annotation?


When a client request for a resource producing application/json content with Accept Header of application/xml. The request fails with HttpMediaTypeNotAcceptableException exception and is wrapped into error message body in the response entity object by using exception handler annotation as mentioned in below code. However, we receive HttpMediaTypeNotAcceptableException again when return values are written to the response with HttpMessageConverter. It is because it checks the producible content type for the response with the acceptable request type, but this is exactly something we are trying to communicate to the client using error message. How do I workaround this issue ? Btw, all the other exceptions are parsing fine to error message. Please advise.

@ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {

     @Override
      protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body,
          HttpHeaders headers, HttpStatus status, WebRequest request) {
          // Setting the response content type to json
          headers.setContentType(MediaType.APPLICATION_JSON);
        return ResponseEntity.status(status).headers(headers).body(body);
      }
    }

Solution

  • Resolved by setting different content negotiation strategy FixedContentNegotiationStrategy for ExceptionHandlerExceptionResolver and HeaderContentNegotiationStrategy for RequestResponseBodyMethodProcessor.