How to properly throw MethodArgumentNotValidException

Mário Sérgio Esteves Alvial :

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ı :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=468892&siteId=1