Java Reference
In-Depth Information
public
public Response getResponse () {...]
}
When JAX-RS sees that a WebApplicationException has been thrown by application code,
it catches the exception and calls its getResponse() method to obtain a Response to send
back to the client. If the application has initialized the WebApplicationException with a
status code or Response object, that code or Response will be used to create the actual
HTTP response. Otherwise, the WebApplicationException will return a status code of 500,
“Internal Server Error,” to the client.
For example, let's say we have a web service that allows clients to query for customers rep-
resented in XML:
@Path ( "/customers" )
public
public class
class CustomerResource
CustomerResource {
@GET
@Path ( "{id}" )
@Produces ( "application/xml" )
public
public Customer getCustomer ( @PathParam ( "id" ) int
int id ) {
Customer cust = findCustomer ( id );
iif ( cust == null
null ) {
throw new WebApplicationException ( Response . Status . NOT_FOUND );
}
return
return cust ;
}
}
In this example, if we do not find a Customer instance with the given ID, we throw a WebAp-
plicationException that causes a 404, “Not Found,” status code to be sent back to the cli-
ent.
Exception Mapping
Many applications have to deal with a multitude of exceptions thrown from application code
and third-party frameworks. Relying on the underlying servlet container to handle the excep-
tion doesn't give us much flexibility. Catching and then wrapping all these exceptions within
WebApplicationException would become quite tedious. Alternatively, you can implement
and register instances of javax.ws.rs.ext.ExceptionMapper . These objects know how to
map a thrown application exception to a Response object:
Search WWH ::




Custom Search