Configuring a JAX-RS response when a ConstraintViolationException is thrown Bean Validation

Bean Validation is a good option for checking objects, but how do I set up a REST API response (using RESTeasy) when thrown ConstraintViolationException?

For instance:

@POST
@Path("company")
@Consumes("application/json")
public void saveCompany(@Valid Company company) {
    ...
}

A request with invalid data will return an HTTP status code 400with the following body:

[PARAMETER]
[saveCompany.arg0.name]
[{company.name.size}]
[a]

Good, but not enough, I would like to normalize such errors in a JSON document.

How can I customize this behavior?

+3
source share
1 answer

Using JAX-RS can be defined ExceptionMapperfor processing ConstraintViolationExceptionwith.

ConstraintViolationException ConstraintViolation, , , , :

@Provider
public class ConstraintViolationExceptionMapper 
       implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {

        List<ValidationError> errors = exception.getConstraintViolations().stream()
                .map(this::toValidationError)
                .collect(Collectors.toList());

        return Response.status(Response.Status.BAD_REQUEST).entity(errors)
                       .type(MediaType.APPLICATION_JSON).build();
    }

    private ValidationError toValidationError(ConstraintViolation constraintViolation) {
        ValidationError error = new ValidationError();
        error.setPath(constraintViolation.getPropertyPath().toString());
        error.setMessage(constraintViolation.getMessage());
        return error;
    }
}
public class ValidationError {

    private String path;
    private String message;

    // Getters and setters
}

JSON, , , JSON.

+3

All Articles