【问题标题】:Jersey bean validation - return validation message for bad requestsJersey bean 验证 - 返回错误请求的验证消息
【发布时间】:2017-08-15 05:07:02
【问题描述】:

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

@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"
}

【问题讨论】:

  • 你应该展示你是如何配置验证器的。

标签: java jersey jersey-2.0


【解决方案1】:

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

}

【讨论】:

  • 在自定义约束验证器中是否可以为每个违反的约束添加多条消息?
  • @Half_Duplex 您可以通过 ex.getConstraintViolations() 从异常中获取违规列表,它们都有自己的消息,您可以根据需要构建响应消息。我只是在 mxb 的回答中使用列表
【解决方案2】:

基于 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();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 2020-06-20
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2014-04-29
    • 2015-12-29
    • 2020-04-28
    相关资源
    最近更新 更多