简体   繁体   中英

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

I'm experimenting with the custom validator annotation with spring boot in my rest application.

here is the sample code from the validator, other requisite classes are present:

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

I made a class annotated with controller advice and exception handler but it doesn't seem to intercept the exception thrown from the validator.

Ok I got it, I extended my controller advice class with ResponseEntityExceptionHandler and did the usual ExceptionHandler annotation specifying my custom exceptions.

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

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