Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
Mário Sérgio Esteves Alvial Avatar asked Mar 17 '18 16:03

Mário Sérgio Esteves Alvial


People also ask

What error does @valid throw?

The exception thrown by @Validated when a constraint we specify is violated is of type ConstraintViolationsException , and has no response handler. To intercept the exception and customize our response, we need to build an exception handler using the @ControllerAdvice and @ExceptionHandler annotations.

How do I instantiate BindingResult?

Errors and BindingResult are interfaces, therefore they cannot be instantiated. Your only option would be to use one of the classes which implements Errors .

What is spring boot validation?

When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument. When the target argument fails to pass the validation, Spring Boot throws a MethodArgumentNotValidException exception.


3 Answers

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
like image 118
Samet Baskıcı Avatar answered Oct 11 '22 22:10

Samet Baskıcı


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
}
like image 32
Bob Jacobsen Avatar answered Oct 11 '22 22:10

Bob Jacobsen


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

https://projectlombok.org/features/SneakyThrows

like image 2
Felipe Mosso Avatar answered Oct 11 '22 20:10

Felipe Mosso