Handling JAX-RS and Bean Validation Errors with MVC

Since JAX-RS 2.0 you can use Bean Validation to validate inputs received from users and outputs created in your application. It’s a handy feature and in most cases it works great. But what if you’re using also MVC and you want to display custom error page if something goes wrong? Or what if you want to handle Bean Validation issues in a slightly different way than JAX-RS implementation you’re using does? This article will give you some answers to these questions.

Topics covered by this article:

Handling Error States with Jersey MVC

In addition to @Template annotation that has been present in Jersey MVC since 2.0 release a @ErrorTemplate annotation has been introduced in Jersey 2.3. The purpose of this annotation is to bind the model to an error view in case an exception has been raised during processing of a request. This is true for any exception thrown after the resource matching phase (i.e. this not only applies to JAX-RS resources but providers and even Jersey runtime as well). The model in this case is the thrown exception itself.

All code samples in this section are taken from shortener-webapp example that is available as sources or as a live demo.

The next snippet shows how to use @ErrorTemplate on a resource method. If all goes well with the method processing, then the /short-link template is used to as page sent to the user. Otherwise if an exception is raised then the /error-form template is shown to the user.

@ErrorTemplate can be used on a resource class or a resource method to merely handle error states. There is no need to use @Template or Viewable with it.

The annotation is handled by custom ExceptionMapper<E extends Throwable> which creates an instance of Viewable that is further processed by Jersey. This exception mapper is registered automatically with any *MvcFeature.

Handling Bean Validation Errors with Jersey MVC

@ErrorTemplate can be used in also with Bean Validation to display specific error pages in case the validation of input/output values fails for some reason. Everything works as described above except the model is not the thrown exception but rather a list of ValidationErrors. This list can be iterated in the template and all the validation errors can be shown to the user in a desirable way.

Let’s add some validation annotations to our resource method from above:

In case the method gets an invalid form parameter (or creates invalid output for a user) we can iterate ValidationErrors in /error-form as follows (Mustache templating engine):

Support for Bean Validation in Jersey MVC Templates is provided by a jersey-mvc-bean-validation extension module. Coordinates of this module are:

org.glassfish.jersey.ext:jersey-mvc-bean-validation:2.5.1

The JAX-RS Feature provided by this module (MvcBeanValidationFeature) has to be registered in order to use this functionality:

Custom Handling of Bean Validation Errors in JAX-RS 2.0

In case the approach described above doesn’t work for you for some reason (i.e. you have implemented your own MVC support or you’re using other JAX-RS 2.0 implementation) you need to follow these steps to achieve similar result as with @ErrorTemplate:

  1. (Jersey specific) add the dependencies on Bean Validation module (jersey-bean-validation) and, optionally, on one of the MVC modules providing support for custom templates (jersey-mvc-*)
  2. create an ExceptionMapper for ConstraintViolationException
  3. register all your providers

I’ll skip the first step as it’s easy enough and we’re going to take a look at creating custom ExceptionMapper and registering it.

Custom ExceptionMapper

Bean Validation runtime throws a ConstraintViolationException when something goes wrong during validating an incoming entity, request parameters or even JAX-RS resource. Every JAX-RS 2.0 implementation is required to provide a standard ExceptionMapper to handle this type of exceptions (ValidationException to be precise) and based on the context return correct HTTP status code (400 or 500). If you want to handle Bean Validation issues differently, you need to write an ExceptionMapper of your own:

With the ExceptionMapper above you’ll be handling all thrown ConstraintViolationExceptions and the final response will have HTTP 400 response status. Entity set (in our case Viewable) to the response will be processed by MessageBodyWriter from Jersey MVC module and it will basically output a processed web-page. The first parameter of the Viewable is path to a template (you can use relative or absolute path), the second is the model the MVC will use for rendering. For more on this topic, refer to the section about MVC in Jersey Users Guide.

Registering Providers

The last step you need to make is to register your providers into your Application (I’ll show you an example using ResourceConfig from Jersey which extends Application class):

More information about how different ways how to register providers and resources is available in this article.

Resources

Sample Application:

Further Reading

MVC Templates
Registering Resources and Providers in Jersey 2
Running Jersey 2 Applications on Heroku