'Ambiguous @ExceptionHandler method for HttpMessageNotReadableException

In my @RestController I'm successfully handling JSONParse exceptions coming from @RequestBody (for example, a String wrongly entered into an Integer field). This is the code:

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({ HttpMessageNotReadableException.class })
public ValidationError handleException(HttpMessageNotReadableException ex) {
    if (ex.getCause() instanceof InvalidFormatException) {
        ...
    } else {
        throw ex;
    }
}

Now I want to move this to a @ControllerAdvice to be used by many controllers. Here it is:

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({ HttpMessageNotReadableException.class })
    public ValidationError handleException(HttpMessageNotReadableException ex) {
        if (ex.getCause() instanceof InvalidFormatException) {
            ...
        } else {
            throw ex;
        }
    }

But Spring complains with the following: Ambiguous @ExceptionHandler method mapped for [class org.springframework.http.converter.HttpMessageNotReadableException]: {public Object foo.bar.RestExceptionHandler.handleException(org.springframework.http.converter.HttpMessageNotReadableException), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}

I can't override ResponseEntityExceptionHandler.handleException because it's final. What other options are there?

Using Spring Boot 2.4.3.



Solution 1:[1]

You should not extend from ResponseEntityExceptionHandler class. Check this answer https://stackoverflow.com/a/71119336/4757784

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emre Zorlu