Defining exception mappers for resource exceptions and errors
Java™ API for RESTful Web Services (JAX-RS) applications can produce exceptions and errors. The default behavior is to use the exception handling functionality of the application container such as JavaServer Pages (JSP) error pages. However, you can customize the error handling and send specific responses back when an exception or error occurs.
About this task
JAX-RS resource methods, like any Java method, can throw checked and unchecked
exceptions. By default, an unchecked runtime exception or error occurs
in the container again. A checked exception is wrapped in a ServletException
for
resources running in the web container. Therefore, a developer can
use error handling facilities such as JSP error pages to handle exceptions
thrown from a JAX-RS application.
JAX-RS introduced the exception, javax.ws.rs.WebApplicationException
.
A developer can specify a specific error class name or javax.ws.rs.core.Response
object
when creating a WebApplicationException
. When the WebApplicationException
is
thrown, the information included in the exception by way of a status
class name or Response object is used to serialize a response.
If
you cannot throw the exception, WebApplicationException
,
in your code and you cannot use the error handling facilities in the
web container, but you want to use a custom error response, then you
can create a customized JAX-RS javax.ws.rs.ext.ExceptionMapper
class
to map exceptions to HTTP error responses.
The following procedure
illustrates how to write a custom ExceptionMapper
class.
Procedure
Results
You have written a custom ExceptionMapper
to
handle exceptions in your JAX-RS web application.