Java Reference
In-Depth Information
public
public interface
interface ExceptionMapper
ExceptionMapper < E extends
extends Throwable > {
{
Response toResponse ( E exception );
}
For example, one exception that is commonly thrown in Java Persistence API (JPA)-based
database applications is javax.persistence.EntityNotFoundException . It is thrown
when JPA cannot find a particular object in the database. Instead of writing code to handle
this exception explicitly, you could write an ExceptionMapper to handle this exception for
you. Let's do that:
@Provider
public
public class
EntityNotFoundMapper
implements
class EntityNotFoundMapper
implements ExceptionMapper < EntityNotFoundException > {
public
public Response toResponse ( EntityNotFoundException e ) {
return
return Response . status ( Response . Status . NOT_FOUND ). build ();
}
}
Our ExceptionMapper implementation must be annotated with the @Provider annotation.
This tells the JAX-RS runtime that it is a component. The class implementing the Excep-
tionMapper interface must provide the parameterized type of the ExceptionMapper . JAX-
RS uses this generic type information to match up thrown exceptions to ExceptionMapper s.
Finally, the toResponse() method receives the thrown exception and creates a Response
object that will be used to build the HTTP response.
JAX-RS supports exception inheritance as well. When an exception is thrown, JAX-RS will
first try to find an ExceptionMapper for that exception's type. If it cannot find one, it will
look for a mapper that can handle the exception's superclass. It will continue this process un-
til there are no more superclasses to match against.
Finally, ExceptionMapper s are registered with the JAX-RS runtime using the deployment
APIs discussed in Chapter 14 .
Exception Hierarchy
JAX-RS 2.0 has added a nice exception hierarchy for various HTTP error conditions. So, in-
stead of creating an instance of WebApplicationException and initializing it with a specific
status code, you can use one of these exceptions instead. We can change our previous ex-
ample to use javax.ws.rs.NotFoundException :
@Path ( "/customers" )
public
public class
class CustomerResource
CustomerResource {
Search WWH ::




Custom Search