Monday, February 15, 2010

Sending HTTP Error Response from JAX-RS Method

Whether you use Apache CXF, Restlet, or Jersey, JAX-RS (JSR-311) gives you a standard way of sending RESTful HTTP Response with error status code.

All you need to do is throw javax.ws.rs.WebApplicationException. You don't have to change the method signature, you can still return the normal domain class when the method is successful.

 @Path("{id}")
 public SessionResource getSession(@PathParam("id") String id) {
  try {
   // ...........
  } catch (IllegalArgumentException e) {
   throw new WebApplicationException(e, Status.NOT_FOUND);
  }
 }
That's it!