[EN] Send custom error messages to client via JAX-RS

Would you like to show custom error messages to your clients via JAX-RS?  Assume that we have a String field in an entity java class and we want to control this String field according to business rules.  Here is the code :

import javax.json.bind.annotation.JsonbCreator;
import javax.json.bind.annotation.JsonbProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.validation.constraints.Size;

* @author altuga
@NamedQuery(name = "all" , query = "select flight from Flight flight")
public class Flight {

  private long id;

  @Size(min = 3, max = 10, message = "stupid users")
  public String number;

  public int numberOfSeats;

  public Flight(@JsonbProperty("number") String number,
            @JsonbProperty("numberOfSeats") int numberOfSeats) {
   this.number = number;
   this.numberOfSeats = numberOfSeats;

  public Flight() {

  public long getId() {
   return id;

We used @Size annotation tag and in order to apply our business. If the user enters below 3 or above 10 then the system will throw a validation exception with a custom messages

import java.net.URI;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

* @author airhacks.com
public class FlightResource {

   FlightCoordinator coordinator;

   public Response save(@Context UriInfo info, @Valid Flight flight) {
    URI uri = info.getAbsolutePathBuilder().path(String.valueOf(flight.getId())).build();
    return Response.created(uri).build();


In order to trigger the validation process, we have to put @Valid annotation just before parameter. In order to show our custom validation message to JAX-RS clients, we have to implement ExceptionMapper class. Here we go :

public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

public Response toResponse(ConstraintViolationException e) {
   List<String> messages = e.getConstraintViolations().stream()

      return Response.status(Status.BAD_REQUEST).entity(messages).build();


ConstraintViolationMapper class will catch the exception and transform it according to your custom messages. In that case “stupid user” message will be sent to the client.



No Comments

Post a Comment