Search code examples
javaspring-bootcontrollerspring-restcontrollerexceptionhandler

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

  • I can't override ResponseEntityExceptionHandler.handleException because it's final

    You're supposed to override the protected ResponseEntity<Object> handleHttpMessageNotReadable(...) method instead for custom error handling.