Home > OS >  How to return a custom response for validation errors using Hibernate Validator and Quarkus
How to return a custom response for validation errors using Hibernate Validator and Quarkus

Time:10-21

I implemented a REST endpoint in my Quarkus application. For validation purpose I'm using the hibernate-validator. So I added the @Valid annotation to the incoming parameter and added some constraints to that class. Everythings works as expected.

When sending a request with invalid data I see a response like this:

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

But I would like to have a more compact response and maybe add some additional information:

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

I found the same question for hibernate-validator and spring-boot: How to return a custom response pojo when request body fails validations that are defined using Bean Validation/Hibernate Validator? But I do not know how to adapt the solutions to Quarkus.

Thanks a lot.

CodePudding user response:

You'll need to provide an implementation of ExceptionMapper<ValidationException>.

Something like:

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

}
  • Related