如何使用Hibernate Validator和Quarkus返回验证错误的自定义响应

isr3a4wc  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(219)

我在Quarkus应用程序中实现了REST端点。出于验证目的,我使用了Hibernate验证器。因此,我向传入参数添加了@Valid注解,并向该类添加了一些约束。一切都按预期进行。
当发送包含无效数据的请求时,我看到如下响应:

{
   "exception": null,
   "propertyViolations": [],
   "classViolations": [],
   "parameterViolations": [   {
      "constraintType": "PARAMETER",
      "path": "aaa.bbb.Id",
      "message": "Id does not match the expected format.",
      "value": "abc"
   }],
   "returnValueViolations": []
}

但我希望有一个更简洁的回应,并可能补充一些额外的信息:

{
   "additional-info": "some text",
   "path": "aaa.bbb.Id",
   "message": "Id does not match the expected format.",
}

我在hibernate-validator和Spring-boot上发现了同样的问题:How to return a custom response pojo when request body fails validations that are defined using Bean Validation/Hibernate Validator?,但我不知道如何使解决方案适应Quarkus。
非常感谢。

gg58donl

gg58donl1#

您需要提供ExceptionMapper<ValidationException>的实现。
类似于:

@Provider
public class ResteasyReactiveViolationExceptionMapper implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException exception) {
         // convert the exception into a response
         // see https://github.com/quarkusio/quarkus/blob/2.13.3.Final/extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/jaxrs/ResteasyReactiveViolationExceptionMapper.java#L32 for inspiration
    }

}

相关问题