问题描述
在我的 @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(...)
方法以进行自定义错误处理。