Hal*_*lex 0 java jersey jersey-2.0
是否可以在响应中返回错误响应的验证注释消息?我认为这是可能的,但我注意到我们的项目没有给出详细的错误请求消息。
@NotNull(message="idField is required")
@Size(min = 1, max = 15)
private String idField;
Run Code Online (Sandbox Code Playgroud)
如果发出缺少 idField 的请求,我希望看到“需要 idField”。我正在使用球衣 2.0。我看到的回应是这样的......
{
"timestamp": 1490216419752,
"status": 400,
"error": "Bad Request",
"message": "Bad Request",
"path": "/api/test"
}
Run Code Online (Sandbox Code Playgroud)
看起来您的 Bean 验证异常 (ConstraintViolationException) 是由您的 ExceptionMappers 之一翻译的。您可以按如下所示注册一个ExceptionMapperforConstraintViolationException并以您想要的格式返回数据。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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2059 次 |
| 最近记录: |