views:

250

answers:

1

I'm developing a REST-ful web service using RESTEasy deployed on Tomcat. I've configured an error page which takes the exception's message and generates an XML based on it when any exception occurs during the request.

This works fine for any application generated exceptions. However, if client sends an invalid XML which cannot be unmarshalled correctly, an javax.xml.bind.UnmarshalException is thrown and Tomcat's default error page is used instead of mine.

I have configured my error page to the error-code 500 in web.xml.

Is using error pages the correct way to handle errors when using RESTEasy or is there an alternative way?

+1  A: 

The best way is to use an ExceptionMapper. You create a class UnmarshalExceptionMapper that implements ExceptionMapper. You annotate this with "@Provider" and in your Application constructor you do "classes.add(UnmarshalExceptionMapper.class)" or "singletons.add(new UnmarshalExceptionMapper())".

Your exception mapper will look something like this:

 @provider
 public class UnmarshalExceptionMapper 
            implements ExceptionMapper<UnmarshalException> {
    public Response toResponse(UnmarshalException exception) {
        ResponseBuilder rb =
            Response.status(
                  Response.Status.BAD_REQUEST)  // Most appropriate HTTP status code
            .entity(your xml goes here)
            .type("application/xml");  
        return rb.build();
   }
 }

Note that you must set the type to "application/xml" because currently content negotiation is NOT done for exception mappers. To do your own content negotiation, get the HttpHeaders from the request, find the "accept" header, and set the type accordingly.

Mark Lutton