是否可以在响应中返回错误响应的验证注释消息?我认为这是可能的,但我注意到我们的项目没有给出详细的错误请求消息。
@NotNull(message="idField is required")
@Size(min = 1, max = 15)
private String idField;
如果发出缺少idField的请求,我想看到“需要idField”。我正在使用球衣2.0。我所看到的回应是......
{
"timestamp": 1490216419752,
"status": 400,
"error": "Bad Request",
"message": "Bad Request",
"path": "/api/test"
}
答案 0 :(得分:4)
看起来你的Bean验证异常(ConstraintViolationException)是由你的一个ExceptionMappers翻译的。您可以为ExceptionMapper
注册ConstraintViolationException
,如下所示,并以您想要的格式返回数据。 ConstraintViolationException
包含您要查找的所有信息。
@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()); // this is the message you are actually looking for
}
return Response.status(Status.BAD_REQUEST).entity(messages).build();
}
}
答案 1 :(得分:0)
在Justin响应的基础上,这是一个使用Java 8流API的版本:
@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException e) {
List<String> messages = e.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList());
return Response.status(Status.BAD_REQUEST).entity(messages).build();
}
}