Reputation: 3136
I wrote an exception mapper to override the response generated by Hibernate Validator so I could have some control over the messaging coming back in the response.
My issue is that I'm having some difficulty finding an easy way to "switch" based on the type of constraint violation and, because of that, I'm having trouble writing custom messages. Ideally, I could have a switch based on the annotation, and return custom messaging in the response. Ideally, it would look something like this:
@Override
public Response toResponse(ConstraintViolationException exception) {
ConstraintViolation violation = exception.getConstraintViolations().iterator().next();
String message = null;
switch (violation.getType()) {
case SomeEnum.NOT_NULL:
message = "It's not null!";
break;
default:
message = "Other message!";
}
...
}
Is something simple like this possible?
Upvotes: 2
Views: 1371
Reputation: 18970
ConstraintViolation#getConstraintDescriptor()
should be helpful to you. Amongst other things, the returned descriptor exposes the violated constraint annotation type:
if ( violation.getConstraintDescriptor().getAnnotation().annotationType() == NotNull.class ) { ... }
That being said, the problem may be better addressed by implementing a custom MessageInterpolator
, which will give you the expected message within the constraint violation right away.
Upvotes: 1