简体   繁体   中英

How to properly throw MethodArgumentNotValidException

I'm trying to get the same result as when I use @Valid in object parameter from a Controller. When the object is invalid an exception (MethodArgumentNotValidException) is throw by my ExceptionHandlerController who has @RestControllerAdvice.

In my case I want to validate an object, but I only can validate it in service layer. The object have bean validation annotations, so I'm trying to programmatically throw MethodArgumentNotValidException for my ExceptionHandlerController handle it, but I'm not having success.

So far I have this:

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();
        }
    }
}

The first parameter is from type MethodParameter and I'm not been able to create this object. Is it the best way to handle my problem?

EDIT 1:

I can't remove the try/catch block. When I remove it I get compile error. How to work around?

You have already handled it by the catch block, you should remove try-catch to your global handler catch it.

then specify the method like below

private void verifyCard(CardRequest card) throws MethodArgumentNotValidException

MethodArgumentNotValidException is a subclass of Exception . This means that it's "checked": To throw it out of your verifyCard(..) method, you have to declare that verifyCard(..) can throw it:

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

If you have lombok dependency in your project, you can also fake compiler by using @SneakyThrows annotation.

https://projectlombok.org/features/SneakyThrows

throw new MethodArgumentNotValidException(null, result);

Above constructor will not work as method parameter is necessary. Valid constructor ( reference ) is:

MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult);

Hence, in your case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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