【问题标题】:Why @ExceptionHandler(MethodArgumentNotValidException.class) is ignored in favour of @ExceptionHandler(Exception.class)为什么 @ExceptionHandler(MethodArgumentNotValidException.class) 被忽略而有利于 @ExceptionHandler(Exception.class)
【发布时间】:2013-10-24 13:34:07
【问题描述】:

我知道 Exception 是所有异常的父级,但我认为当您使用特定异常类设置 @ExceptionHandler 时,它应该处理该特定异常。

也许您可以指出我在以下代码中遗漏的内容,因此 MethodArgumentNotValidException 将进入 processValidationError 方法而不是 processError 方法。

@ControllerAdvice
public class ExceptionHandler {

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ValidationErrorDTO processError(Exception e) {
    return processErrors(e);
  }
 }

  @ControllerAdvice
public class OtherExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    return processErrors(ex);
}
}

【问题讨论】:

  • 您确定抛出了MethodArgumentNotValidException 而不是某个包装类吗?
  • @SotiriosDelimanolis,your answer 不会在这里帮忙吗? :)
  • @MichałRybak 好像 OP 只有一个 @ControllerAdvice 类。

标签: java spring spring-mvc exception-handling


【解决方案1】:

在您编辑之后,很明显您有多个 @ControllerAdvice 类。

简而言之,问题在于您的ExceptionHandler 类(及其@ExceptionHandlerException.class)首先由Spring 注册,并且因为Exception 处理程序匹配任何异常,它将在Spring 获取之前匹配到定义的更具体的处理程序。

您可以在@Sotirios answer here阅读详细说明。

【讨论】:

    【解决方案2】:

    我建议您只注册一个ControllerAdvice 并确保它扩展ResponseEntityExceptionHandler,因此MethodArgumentNotValidException 的默认处理不会被覆盖。

    如果您希望更改处理MethodArumentNotValidException 的逻辑,您可以覆盖handleMethodArgumentNotValid 方法。

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 2018-11-16
      • 2021-05-29
      • 2016-08-15
      • 2021-12-08
      • 2018-12-03
      • 2019-06-28
      • 2021-11-02
      • 2012-06-02
      相关资源
      最近更新 更多