0

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.

askwer
  • 163
  • 13
  • If you just want to show some custom message to a client depending on the error - look how to implement it without using exceptions here: https://stackoverflow.com/questions/19825563/custom-validator-message-throwing-exception-in-implementation-of-constraintvali If you want to use exceptions try to catch `ValidationException` in your `ControllerAdvice` and get its `Throwable` cause, because Hibernate validator (which is use by spring-boot) wraps all exceptions in this default exception – Andrei Titov Aug 23 '22 at 09:57
  • Thanks, I will try it and report back. – askwer Aug 23 '22 at 10:00

1 Answers1

0

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
    }
}
askwer
  • 163
  • 13