【问题标题】:How to properly throw MethodArgumentNotValidException如何正确抛出 MethodArgumentNotValidException
【发布时间】:2018-03-17 16:47:54
【问题描述】:

我试图获得与在控制器的对象参数中使用 @Valid 时相同的结果。当对象无效时,我的具有@RestControllerAdvice 的 ExceptionHandlerController 会抛出异常 (MethodArgumentNotValidException)。

在我的例子中,我想验证一个对象,但我只能在服务层验证它。该对象有 bean 验证注释,所以我试图以编程方式抛出 MethodArgumentNotValidException 让我的 ExceptionHandlerController 处理它,但我没有成功。

到目前为止,我有这个:

private void verifyCard(CardRequest card) {
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(card, "card");
    SpringValidatorAdapter adapter = new SpringValidatorAdapter(this.validator);
    adapter.validate(card, result);

    if (result.hasErrors()) {
        try {
            throw new MethodArgumentNotValidException(null, result);
        } catch (MethodArgumentNotValidException e) {
            e.printStackTrace();
        }
    }
}

第一个参数来自 MethodParameter 类型,我无法创建此对象。这是解决我的问题的最佳方式吗?

编辑 1:

我无法删除 try/catch 块。当我删除它时,我得到编译错误。如何解决?

【问题讨论】:

  • 编译错误是什么?

标签: java spring spring-boot bean-validation


【解决方案1】:

您已经通过catch 块处理了它,您应该将try-catch 删除到您的全局处理程序中捕获它。

然后像下面这样指定方法

private void verifyCard(CardRequest card) throws MethodArgumentNotValidException

【讨论】:

  • 像这样指定方法:private void verifyCard(CardRequest card) throws MethodArgumentNotValidException
【解决方案2】:

MethodArgumentNotValidExceptionException 的子类。这意味着它已被“检查”:要将其从您的 verifyCard(..) 方法中抛出,您必须声明 verifyCard(..) 可以抛出它:

private void verifyCard(CardRequest card) throws MethodArgumentNotValidException {
// your code
}

【讨论】:

    【解决方案3】:

    如果你的项目中有lombok 依赖,你也可以使用@SneakyThrows 注解来伪造编译器。

    https://projectlombok.org/features/SneakyThrows

    【讨论】:

      【解决方案4】:
      throw new MethodArgumentNotValidException(null, result);
      

      上面的构造函数将不起作用,因为方法参数是必需的。 有效的构造函数 (reference) 是:

      MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult);
      

      因此,在你的情况下:

      throw new MethodArgumentNotValidException(new MethodParameter(
      this.getClass().getDeclaredMethod("verifyCard", YourClassName.class), 0), errors);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-03
        • 1970-01-01
        • 2014-06-06
        • 1970-01-01
        • 2017-10-18
        • 2022-01-22
        • 2015-07-09
        • 1970-01-01
        相关资源
        最近更新 更多