Global Exception Handling in Jersey

Yes. JAX-RS has a concept of ExceptionMappers. You can create your own ExceptionMapper interface to map any exception to a response. For more info see: https://jersey.github.io/documentation/latest/representations.html#d0e6352


javax.ws.rs.ext.ExceptionMapper is your friend.

Source: https://jersey.java.net/documentation/latest/representations.html#d0e6665

Example:

@Provider
public class EntityNotFoundMapper implements ExceptionMapper<javax.persistence.EntityNotFoundException> {
  public Response toResponse(javax.persistence.EntityNotFoundException ex) {
    return Response.status(404).
      entity(ex.getMessage()).
      type("text/plain").
      build();
  }
}

Tags:

Java

Rest

Jersey