ConstraintViolationException

ConstraintViolationException

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

@NotNull(message="idField is required")
@Size(min = 1, max = 15)
private String idField;


如果发出缺少idField的请求,我想返回“ idField is required”。我正在使用jersey 2.0。我看到的是回应...

{
  "timestamp": 1490216419752,
  "status": 400,
  "error": "Bad Request",
  "message": "Bad Request",
  "path": "/api/test"
}

最佳答案

看来您的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();
  }

}

09-26 00:04