【问题标题】:Customizing JAX-RS response when a ConstraintViolationException is thrown by Bean Validation当 Bean Validation 抛出 ConstraintViolationException 时自定义 JAX-RS 响应
【发布时间】:2017-06-01 12:53:25
【问题描述】:

Bean Validation 是验证对象的好选择,但如何自定义 REST API(使用 RESTeasy)在抛出 ConstraintViolationException 时的响应?

例如:

@POST
@Path("company")
@Consumes("application/json")
public void saveCompany(@Valid Company company) {
    ...
}

包含无效数据的请求将返回带有以下正文的 HTTP 400 状态代码:

[PARAMETER]
[saveCompany.arg0.name]
[{company.name.size}]
[a]

这很好但还不够,我想在 JSON 文档中规范化这些类型的错误。

如何自定义此行为?

【问题讨论】:

标签: java rest jax-rs resteasy bean-validation


【解决方案1】:

使用 JAX-RS 可以定义一个ExceptionMapper 来处理ConstraintViolationExceptions。

从ConstraintViolationException,您可以获得一组ConstraintViolation,它公开了约束违反上下文,然后将您需要的详细信息映射到一个任意类并在响应中返回:

@Provider
public class ConstraintViolationExceptionMapper 
       implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {

        List<ValidationError> errors = exception.getConstraintViolations().stream()
                .map(this::toValidationError)
                .collect(Collectors.toList());

        return Response.status(Response.Status.BAD_REQUEST).entity(errors)
                       .type(MediaType.APPLICATION_JSON).build();
    }

    private ValidationError toValidationError(ConstraintViolation constraintViolation) {
        ValidationError error = new ValidationError();
        error.setPath(constraintViolation.getPropertyPath().toString());
        error.setMessage(constraintViolation.getMessage());
        return error;
    }
}
public class ValidationError {

    private String path;
    private String message;

    // Getters and setters
}

如果您使用 Jackson 进行 JSON 解析,您可能想看看这个 answer,它展示了如何获取实际 JSON 属性的值。

【讨论】:

  • 谢谢,但提供者似乎被忽略了! (resteasy 3.0.19.Final,wildfly 10.1.0.final),有什么提示吗?
  • @Francois 你的应用是什么样的?你有web.xml 吗?你扩展Application吗?欢迎更多详细信息为您提供帮助。
  • 是的,我有一个 web.xml,但它是空的,我有一个经典的 rest api 应用程序 @ApplicationPath("/") public class ApplicationConfig extends Application { @SuppressWarnings("unchecked") public Set > getClasses() { return new HashSet>(Arrays.asList(CustomerService.class)); } }
  • @Francois 您正在覆盖getClasses() 方法,因此自动扫描不会自动选择提供程序。也注册提供者:return new HashSet&lt;&gt;(Arrays.asList(CustomerService.class, ConstraintViolationExceptionMapper.class));
  • 非常简单的构造!干得好
猜你喜欢
  • 1970-01-01
  • 2015-10-07
  • 2013-06-09
  • 2015-01-03
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
相关资源
最近更新 更多