Skip to Content
RESTful Java with JAX-RS
book

RESTful Java with JAX-RS

by Bill Burke
November 2009
Intermediate to advanced
310 pages
7h 42m
English
O'Reilly Media, Inc.
Content preview from RESTful Java with JAX-RS

Chapter 20. Examples for Chapter 7

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.

Example ex07_1: 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")
public class CustomerResource {
...
   @GET
   @Path("{id}")
   @Produces("application/xml")
   public Customer getCustomer(@PathParam("id") int id)
   {
      Customer customer = customerDB.get(id);
      if (customer == null)
      {
         throw new NotFoundException("Could not find customer "
                                      + id);
      }
      return customer;
   }

   @PUT
   @Path("{id}")
   @Consumes("application/xml")
   public void updateCustomer(@PathParam("id") int id,
                              Customer update)
   {
      Customer current = customerDB.get(id);
      if (current == null)
        throw new NotFoundException("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 updateCustomer() methods threw a javax.ws.rs.WebApplicationException ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

RESTful Java with JAX-RS 2.0, 2nd Edition

RESTful Java with JAX-RS 2.0, 2nd Edition

Bill Burke
RESTful Java Web Services - Third Edition

RESTful Java Web Services - Third Edition

Balachandar Bogunuva Mohanram

Publisher Resources

ISBN: 9780596809300Supplemental ContentErrata Page