The ValidationError class of jersey2.x looks something like this
@XmlRootElement
public final class ValidationError {
private String message;
private String messageTemplate;
private String path;
private String invalidValue;
...
}
which when error occurs returns string like this
Contact with given ID does not exist. (path = ContactCardResource.getContact.<return value>, invalidValue = null)
But what i need is consistent error message response interface for client . Which should send back only string messages . So this should not include class name and method name .For Some validation which dosen't depend on bean validation ,For example duplicate username . I just send string with 400 or 500 status code . I want to do same with Bean Validation how can this be achieved
Bean-Validation throws ConstraintViolationException
and you can write a custom exception mapper to handle ConstraintViolationException
as shown below.
@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException e) {
// There can be multiple constraint Violations
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
List<String> messages = new ArrayList<>();
for (ConstraintViolation<?> violation : violations) {
messages.add(violation.getMessage());
}
return Response.status(Status.BAD_REQUEST).entity(StringUtils.join(messages,";")).build();
}
}
Register above mapper in your ResourceConfig
or Appication
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.