问题
I am trying to create a custom validator and mapped it into a specific constraintViolationException. The reason is I want to create different custom exception for different constraint. For example, if a user is not found in the database, a not found violationException is triggered, while if the user has invalid username, a bad response violationException will be executed instead.
@Retention(RUNTIME)
@Target({ FIELD, METHOD })
@Constraint(validatedBy = UserNotValidValidator.class)
public @interface UserIsValid { ... }
mapped into
public class ConstraintExceptionMapper implements
ExceptionMapper<ConstraintViolationException> {
public Response toResponse(ConstraintViolationException e) { ... }
}
To be more specific, the question is whether bean hibernate validator supports multiple constraint exception mapper.
回答1:
Exception mappers are a concept of JAX-RS not of Bean Validation. You should create one exception mapper for ConstraintViolationException
and have it create different responses based on the violations contained within a given violation exception. E.g. you can examine the violated constraint type via `ConstraintViolation.getConstraintDescriptor().getAnnotation().annotationType().
来源:https://stackoverflow.com/questions/20275630/mapping-specific-constraint-validator-to-specific-contraintviolationexception-in