Bean验证引发ConstraintViolationException时自定义JAX-RS响应 [英] Customizing JAX-RS response when a ConstraintViolationException is thrown by Bean Validation
问题描述
Bean Validation是验证对象的一个很好的选项,但是当抛出 ConstraintViolationException
时,如何自定义REST API的响应(使用RESTeasy)?
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?
例如:
@POST
@Path("company")
@Consumes("application/json")
public void saveCompany(@Valid Company company) {
...
}
包含无效数据的请求将返回HTTP 400
状态具有以下正文的代码:
A request with invalid data will return a HTTP 400
status code with the following body:
[PARAMETER]
[saveCompany.arg0.name]
[{company.name.size}]
[a]
这很好,但还不够,我想在JSON文档中规范化这类错误。
It's nice but not enough, I would like to normalize these kind of errors in a JSON document.
如何自定义此行为?
推荐答案
使用JAX-RS可以定义 ExceptionMapper
处理 ConstraintViolationException
s。
With JAX-RS can define an ExceptionMapper
to handle ConstraintViolationException
s.
来自 ConstraintViolationException
,您可以获得一组 ConstraintViolation
,公开约束违规上下文,然后将您需要的详细信息映射到abitrary类并返回响应:
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
}
如果您使用Jackson进行JSON解析,您可能需要查看此答案 ,显示如何获取实际JSON属性的值。
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.
这篇关于Bean验证引发ConstraintViolationException时自定义JAX-RS响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!