Close

JAX-RS - Exception Mapping Provider

[Last Updated: Jul 9, 2017]

In JAX-RS the exception mapping providers map a checked or runtime exception to an instance of Response.

To provide exception mapping, we have to write a class which implements the ExceptionMapper<E extends Throwable> interface. This class may be annotated with @Provider for automatic discovery and registration.

To map an exception to a mapper, JAX-RS runtime implementation, selects the mapper whose generic type is the nearest superclass of the exception.

The ExceptionMapper interface

package javax.ws.rs.ext;

import javax.ws.rs.core.Response;

public interface ExceptionMapper<E extends Throwable> {

    Response toResponse(E exception);
}

Example

Implementing ExceptionMapper

@Provider
public class InvalidIdExceptionMapper
        implements ExceptionMapper<InvalidIdException> {


    @Override
    public Response toResponse(InvalidIdException exception) {
        return Response.status(Response.Status.NOT_FOUND)
                       .entity(prepareMessage(exception))
                       .type("text/plain")
                       .build();
    }

    private String prepareMessage(InvalidIdException exception) {

        String m = exception.getMessage();
        String r = "Invalid request.\n";
        r += String.format("Error Message: %s.%nError Type: %s.%n"
                        + "You may contact admin@example.com for more questions.",
                m, exception.getClass());
        return r;
    }
}
public class InvalidIdException extends RuntimeException {

    public InvalidIdException(String message) {
        super(message);
    }
}

Writing a JAX-RS resource

@Path("/employees")
public class EmployeeResource {

    @GET
    @Path("{id}")
    public String getEmployeeId(@PathParam("id") String employeeId) {
        return EmployeeService.Instance.getEmployeeById(employeeId);
    }
}
public enum EmployeeService {
    Instance;

    public String getEmployeeById(String id) {
        try {
            long l = Long.parseLong(id);
            //just a dummy response
            return "employee" + l;
        } catch (NumberFormatException e) {
            throw new InvalidIdException("Employee id is not valid, " + id);
        }

    }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Using HTTPie to access the resource:

Example Project

Dependencies and Technologies Used:

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • JDK 1.8
  • Maven 3.3.9

JAX-RS ExceptionMapper Example Select All Download
  • exception-mapper-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • InvalidIdExceptionMapper.java

    See Also