no error message when custom constraint gets violated

Go To StackoverFlow.com

0

I have the following code for my custom Constraint:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
@Constraint(validatedBy = MinMaxValidator.class)
public @interface CheckMinMax{

    String message() default "MinMax constraint has been violated";

    Class<? extends Payload>[] payload() default {};

    Class<?>[] groups() default {};

    int min() default 1;

    int max() default 10;
}

And the Validator class:

public class MinMaxValidator implements ConstraintValidator {

int max;
int min;

@Override
public void initialize(CheckMinMax annotation) {
    max = annotation.max();
    min = annotation.min();

}

@Override
public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
    if (value < min || value > max)
        return false;
    return true;
}

}

now when i annotate my entitybean whith my annotation and try to pass in an object which violates my constraint with following code:

validator.validate(obj);

it works, but there is no error message... Is here something missing? How can i manage it to output the default error message "MinMax constraint has been violated" ?

thx

2012-04-03 20:57
by Moonlit


0

I figured it out how you can print out the error message defined in the Annotation:

Set<ConstraintViolation<TypeOfObj> cvs = validator.validate(obj);
for(ConstraintViolation<TypeOfObj> violation : cvs) 
{
    logger.info(violation.getMessage());
}

cheers

2012-04-05 22:51
by Moonlit


1

Validator.validate() method is not throwing the ConstraintValidationException. It returns Set<ConstraintViolation>, you are responsible for throwing the exception if there are any constraint violations.

The typical usage pattern would be:

Set<ConstraintViolation> cvs = validator.validate(obj);
if(cvs.size() > 0){
  throw new ConstraintViolationException(cvs);
}
2012-04-03 21:35
by Piotr Kochański
hi and thank you for your answer. the set requires a type parameter. Set> cvs; But the constructor of ConstraintViolationException don't accept it. (The constructor ConstraintViolationException(Set>) is undefined) : - Moonlit 2012-04-03 22:46
Ads