2017-03-22 75 views
0

是否可以在响应错误响应中返回验证注释消息?我认为这是可能的,但我注意到我们的项目没有收到详细的错误请求消息。Jersey bean验证 - 返回不良请求的验证消息

@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

您应该展示如何配置验证器。 – davidxxx

回答

2

它看起来像你的Bean验证异常(ConstraintViolationException)是由你的一个ExceptionMappers翻译的。您可以注册一个ExceptionMapperConstraintViolationException如下所示,并以您想要的格式返回数据。 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(); 
    } 

} 
+0

在自定义约束验证程序中是否有一种方法可以为违反的每个约束添加多条消息? –