Ambiguous @ExceptionHandler method for HttpMessageNotReadableException

4.1k Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

If you're dealing with this in 2023, try using this

@ControllerAdvice
public class GlobalControllerExceptionHandler extends 
ResponseEntityExceptionHandler {

    ...

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        ...
        return new ResponseEntity<>(...); 
    }

    ...

}

HttpStatus has changed to HttpStatusCode.

0
On

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