In order to get your custom exception and message, you can catch the ValidationException
thrown by the validation framework and extract your custom exception and message from it.
Something like this should work.
public class CustomValidator implements ConstraintValidator<CustomClass, CharSequence> {
@Override
public void initialize(CustomClass annota) {
try {
// code
} catch (ValidationException e) {
/* if an exception is thrown in the initialize method, the validation framework will not execute the isValid method. */
throw new CustomException("validation error", e);
} catch (Exception e) {
throw new CustomException("custom error", e);
}
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
try {
// validation logic
return true;
} catch (CustomException e) {
// catch and rethrow your custom exception
throw e;
} catch (ValidationException e) {
// catch and extract your custom exception and message
Throwable cause = e.getCause();
if (cause instanceof CustomException) {
CustomException customException = (CustomException) cause;
String message = customException.getMessage();
// do something with customException and message
}
throw e;
}
}
}
the isValid
method is the main method used by the validation framework to determine if an object is valid or not, and it is necessary to implement it in order to define the validation logic. Even if an exception is thrown in the initialize method, the isValid
method is still necessary and will be executed for valid objects.