November 2013
Intermediate to advanced
392 pages
8h 59m
English
In Chapter 7, you learned how to create complex responses using the Response and ResponseBuilder classes. You also learned how to map thrown exceptions to a Response using a javax.ws.rs.ext.ExceptionMapper. Since most of our examples use a Response object in one way or another, this chapter focuses only on writing an ExceptionMapper.
This example is a slight modification from ex06_1 to show you how you can use ExceptionMappers. Let’s take a look at the CustomerResource class to see what is different:
src/main/java/com/restfully/shop/services/CustomerResource.java
@Path("/customers")publicclassCustomerResource{...@GET@Path("{id}")@Produces("application/xml")publicCustomergetCustomer(@PathParam("id")intid){Customercustomer=customerDB.get(id);if(customer==null){thrownewCustomerNotFoundException("Could not find customer "+id);}returncustomer;}@PUT@Path("{id}")@Consumes("application/xml")publicvoidupdateCustomer(@PathParam("id")intid,Customerupdate){Customercurrent=customerDB.get(id);if(current==null)thrownewCustomerNotFoundException("Could not find customer "+id);current.setFirstName(update.getFirstName());current.setLastName(update.getLastName());current.setStreet(update.getStreet());current.setState(update.getState());current.setZip(update.getZip());current.setCountry(update.getCountry());}}
In ex06_1, our getCustomer() and
Read now
Unlock full access