Search code examples
bean-validationopen-liberty

How can I return a custom reponse for a bean validation error under Open Liberty?


We are using beanValidation-2.0 and cdi-2.0 under Open Liberty 20.0.0.3. This works fine in that Open Liberty returns a 400 Bad Request response containing the bean validation error message when a a bean validation error is detected. I would like to update our application to instead return a custom response when Open Liberty detects a bean validation error. Is there a way that I can somehow "intercept" the bean validation error (or the Open Liberty generated response) and return my own custom response?`


Solution

  • Usually when you get a validation error, a ConstraintViolationException is thrown and you should be able to catch that and create your own response.

    If you're using JAX-RS, you might want to do this by creating and registering an ExceptionMapper to handle this type of exception and turn it into a response. There's an example here.