You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.

Exception Handling

Errors can be reported to a client either by creating and returning the appropriate Response object or by throwing an exception. Application code is allowed to throw any checked (classes extending java.lang.Exception) or unchecked (classes extending java.lang.RuntimeException) exceptions they want. Thrown exceptions are handled by the JAX-RS runtime if you have registered an exception mapper. Exception mappers can convert an exception to an HTTP response. If the thrown exception is not handled by a mapper, it is propagated and handled by the container (i.e., servlet) JAX-RS is running within. JAX-RS also provides the This can be thrown by application code and automatically processed by JAX-RS without having to write an explicit mapper. Let’s look at how to use the WebApplicationException first. We’ll then examine how to write your own specific exception mappers.

JAX-RS has a built-in unchecked exception that applications can throw. This exception is preinitialized with either a Response or a particular status code:

public class WebApplicationException extends RuntimeException { public WebApplicationException() {...} public WebApplicationException(Response response) {...} public WebApplicationException(int status) {...} public WebApplicationException(Response.Status status) {...} public WebApplicationException(Throwable cause) {...} public WebApplicationException(Throwable cause, Response response) ...

The best content for your career. Discover unlimited learning on demand for around $1/day.