RESTful ConstraintViolationMapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {
	@Override
	public Response toResponse(ConstraintViolationException exception) {
		// Extract constraint violations
		Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
		// Construct error messages
		List<String> messages = new ArrayList<>();
		for (ConstraintViolation<?> violation : violations) {
			messages.add(violation.getMessage());
		}
		// Construct custom error response
		return Response.status(Response.Status.BAD_REQUEST)
				.entity(new RestErrorResponse(String.join(",", messages)))
				.type(MediaType.APPLICATION_JSON)
				.build();
	}
}
 This post is licensed under  CC BY 4.0  by the author.