O'Reilly logo

RESTful Java with JAX-RS by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 javax.ws.rs.WebApplicationException. 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.

javax.ws.rs.WebApplicationException

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required