public void updateCustomer(@PathParam("id") int id,
Customer update)
{
Customer current = customerDB.get(id);
if (current == null)
throw new CustomerNotFoundException("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. We’ve replaced this exception with our own
custom class, CustomerNotFoundException:
src/main/java/com/restfully/shop/services/CustomerNotFoundException.java
public class CustomerNotFoundException extends RuntimeException
{
public NotFoundException(String s)
{
super(s);
}
}
There’s nothing really special about this exception class other than it inherits from
java.lang.RuntimeException. What we are going to do, though, is map this thrown
exception to a Response object using an ExceptionMapper:
src/main/java/com/restfully/shop/services/CustomerNotFoundExceptionMapper.java
@Provider
public class NotFoundExceptionMapper
implements ExceptionMapper
{
public Response toResponse(NotFoundException exception)
{
return Response.status(Response.Status.NOT_FOUND)
.entity(exception.getMessage())
.type("text/plain").build();
}
}
288
|
Chapter 22: Examples for Chapter 7
www.it-ebooks.info
When a client makes a GET request to a customer URL that does not exist, the Custom
erResource.getCustomer() method throws a CustomerNotFoundException. This ex‐
ception is caught by the JAX-RS runtime, and the NotFoundExceptionMapper.toRes
ponse() method is called. This method creates a Response object that returns a 404
status code and a plain-text error message.
The last thing we have to do is modify our Application class to register the Exception
Mapper:
src/main/java/com/restfully/shop/services/ShoppingApplication.java
public class ShoppingApplication extends Application {
private Set