JAX-RS - Exception Mapping Provider

[Updated: Jul 9, 2017, Created: 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



public interface ExceptionMapper<E extends Throwable> {

    Response toResponse(E exception);


Implementing ExceptionMapper

public class InvalidIdExceptionMapper
      implements ExceptionMapper<InvalidIdException> {

  public Response toResponse(InvalidIdException exception) {
      return Response.status(Response.Status.NOT_FOUND)

  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 for more questions.",
              m, exception.getClass());
      return r;
public class InvalidIdException extends RuntimeException {

  public InvalidIdException(String message) {

Writing a JAX-RS resource

public class EmployeeResource {

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

  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


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

See Also