How to properly throw MethodArgumentNotValidException

11,307

Solution 1

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

Solution 2

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
}

Solution 3

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

https://projectlombok.org/features/SneakyThrows

Share:
11,307
Mário Sérgio Esteves Alvial
Author by

Mário Sérgio Esteves Alvial

Updated on July 20, 2022

Comments

  • Mário Sérgio Esteves Alvial
    Mário Sérgio Esteves Alvial almost 2 years

    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?

  • Samet Baskıcı
    Samet Baskıcı about 6 years
    specify the method like this : private void verifyCard(CardRequest card) throws MethodArgumentNotValidException