News Ticker

Handle Bean Validation Failure

Java EE JAX-RS How to handle bean validation failures Java EE JAX-RS How to handle bean validation failures

How JAX-RS Handles Validation Failure

A bean validation failure results is a “400 Bad Request” response from the server. Let’s learn how to respond to the client with a more informative response.

Two Ways to Handle Failures

Two technique to report data integrity violations to the client are:

  • respond to the client with a list of problem fields in a custom key-value pair HTTP header and
  • use the response’s body to encapsulate the error response.

Both techniques have their pros and cons. The choice you make will depend on your business model and clients requirements. In either case, you need to document it well, so that a front end developer knows how to use the error response.


Learn Bean Validation with JAX-RS

Custom Key-Value Pair HTTP Header

Let’s look at the first technique.

I am going to present one way to handle the list of problem fields in the response body. As there is no accepted convention you are free to design your own structure.

I will use is a map of the property names and a message detailing what caused the validation failure.

Implement an Exception Manager

In both cases, we must implement an exception manager for the ConstraintViolationException. This exception contains a set of ConstraintViolation objects each representing the violation.

The Constraint Violation Exception

The ConstraintViolation instance contains a lot of useful information about the violation, such as the field name and the violation message. We can use this information to construct a response to the client. To do so, extract the field names and the error messages, turning the set into a stream, and collecting it to a map like so.

final Map<String, String> errorResponse =
      .collect(Collectors.toMap(o -> o.getPropertyPath().toString(), o -> o.getMessage()));

Add Errors to Response Body

We then wrap the map in a custom POJO which has one field, a map. I call the custom POJO DataIntegrityValidation. Then add it to the response body in the same way we have done so before.

return Response
         .entity(new DataIntegrityValidation(errorResponse))

Now the response HTTP body will contain a response similar to that which you see here.

  "errorResponse": {
  "entry": [{
      "key": "description",
      "value": "size must be between 100 and 2147483647"
      "key": "published",
      "value": "must be in the past"
      "key": "link",
      "value": "must match \"^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$\""

You will notice that there is a message for each bean violation. The Bean Validation API adds this for us, so we don’t have to.

However, we can customize this messages. Pass the custom message to the constraint annotations as metadata. It is possible to internationalize it so that the response appears in the client’s own language. This is beyond the scope of this article, but I encourage you to seek out examples of how to do this.

Encapsulate the Error Response

Let’s look at the second way to report violation issues to the client.

This way collects that same information as before and puts it in a custom HTTP header field. As before, extract violation data from the ConstraintViolationException and produce a comma separated String of the errors.

final String message = 
      .map(cv -> extractPropertyName(cv.getPropertyPath().toString()) + " : " + cv.getMessage())
      .collect(Collectors.joining(", "));

we can then add this to the response:

return Response
         .header("X-Validation-Failure", message)

Use a Custom Header

The response includes the custom header “X-Validation-Failure”, whose value is the message string. It is the convention to prefix custom headers with a capital X followed by a string that describes the headers purpose.

This then adds the following string to the HTTP header response.

link : must match "^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$", 
published : must be in the past, 
description : size must be between 100 and 2147483647

You will see that it contains the same data as the previous example.

Learn More

I tackle how to handle bean validation in a RESTful API in my new course RESTful Service with JAX-RS 2.0. You will learn Bean Validation Management and much more. You can watch a preview of how to manage validation failures here.

1 Comment on Handle Bean Validation Failure

  1. Hi admin, i must say you have hi quality posts here.
    Your blog should go viral. You need initial traffic boost only.
    How to get it? Search for; Mertiso’s tips go viral

Leave a Reply

%d bloggers like this: