繁体   English   中英

是否可以在 Spring Boot 中拦截自定义注释验证器引发的异常?

[英]Is it possible to intercept an exception thrown from a custom annotation validator in Spring Boot?

我正在我的 rest 应用程序中尝试使用 spring 引导的自定义验证器注释。

这是来自验证器的示例代码,还有其他必需的类:

public class CustomerValidator implements ConstraintValidator<CustomerValidation, Customer>
{
    public boolean isValid(Customer value, ConstraintValidatorContext cxt) {
   
        if(value.getItemList.size() == 0) {
            throw new CustomerOrderException();
        }

        if(value.getBalance() < value.getCost()) {
            throw new InsufficientBalanceException();
        }

        return true;
    }
}

我做了一个 class 注释 controller 建议和异常处理程序,但它似乎没有拦截从验证器抛出的异常。

好的,我明白了,我使用 ResponseEntityExceptionHandler 扩展了我的 controller 建议 class 并使用了通常的 ExceptionHandler 注释来指定我的自定义异常。

public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value={CustomerOrderException.class})
    protected ResponseEntity<Object> handleException(CustomerOrderException ex, WebRequest request) {
        //return response entity
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM