HttpMessageNotReadableException 的模糊 @ExceptionHandler 方法

问题描述

在我的 @RestController 中,我成功地处理了来自 @RequestBody 的 JSONParse 异常(例如,错误地将字符串输入到整数字段中)。这是代码

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

现在我想把它移到一个 @ControllerAdvice 以供许多控制器使用。这是:

@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;
        }
    }

但是 Spring 抱怨以下内容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}

我无法覆盖 ResponseEntityExceptionHandler.handleException,因为它是最终的。还有哪些其他选择?

使用 Spring Boot 2.4.3。

解决方法

我无法覆盖 ResponseEntityExceptionHandler.handleException 因为它是最终的

您应该重写 protected ResponseEntity<Object> handleHttpMessageNotReadable(...) 方法以进行自定义错误处理。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...