Customizing JAX-RS response when a ConstraintViolationException is thrown by Bean Validation

隐身守侯 提交于 2019-12-01 02:52:41

问题


Bean Validation is a good option to validate objects, but how to customize the response of a REST API (using RESTeasy) when a ConstraintViolationException is thrown?

For example:

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

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

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

It's nice but not enough, I would like to normalize these kind of errors in a JSON document.

How can I customize this behavior?


回答1:


With JAX-RS can define an ExceptionMapper to handle ConstraintViolationExceptions.

From the ConstraintViolationException, you can get a set of ConstraintViolation, that exposes the constraint violation context, then map the details you need to an abitrary class and return in the response:

@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
}

If you use Jackson for JSON parsing, you may want to have a look at this answer, showing how to get the value of the actual JSON property.



来源:https://stackoverflow.com/questions/44308101/customizing-jax-rs-response-when-a-constraintviolationexception-is-thrown-by-bea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!