users@jersey.java.net

Error Handling...and forwarding

From: Jorge L Williams <Jorge.Williams_at_inl.gov>
Date: Thu, 11 Dec 2008 16:32:02 -0700

Hey guys,

I know we covered this topic earlier, but I have a slightly different
question, I think.

We want to make sure that regardless of what sort of error condition
occurs (whether it's generated by one of our JAX-RS resources or whether
it's an internal server error of some kind) that we return a correct
entity. In our case we have a JAXB object called WebserviceFault that our
clients expect should anything go wrong.

To catch every case we created an ErrorServlet that mapped to say /error
and setup our web.xml...

  <error-page>
    <error-code>400</error-code>
    <location>/error</location>
  </error-page>
  .
  .
  .
 <error-page>
    <error-code>500</error-code>
    <location>/error</location>
  </error-page>

The error servlet itself simply gets details from the request...

        Integer code = (Integer) request.getAttribute
("javax.servlet.error.status_code");
        Exception e = (Exception) request.getAttribute
("javax.servlet.error.exception");
        String msg = (String) request.getAttribute
("javax.servlet.error.message");

and wraps it around a WebserviceFault which it serializes to the response.

Very tedious and maybe a little goofy (If there's a better way I'll take
it), but it's been working well for us thus far and this method allows us
to catch absolutely all error conditions including 401s etc..that I don't
think make it into Jersey.

We've been transitioning our ReST services from using vanilla servlets to
Jersey over the last couple of months. I decided to replace the
ErrorServlet that we've been using with an error resource since we've
become interested in receiving error conditions not just in XML but also
in JSON and I figured converting the Error servlet would be the easiest
way to accomplish this.

One problem: it doesn't work. When an error condition hits and the
application server forwards to the error resource, I get nothing but a
blank request no entity at all -- though the Error code is correctly
transmitted ie:


HTTP/1.x 404 Not Found
Date: Thu, 11 Dec 2008 22:34:21 GMT
Content-Length: 0

I suspect that this is because the request is being forwarded and the URI
is not what Jersey is expecting(?).
For example we get...

GET /bla/bla/bla

but something goes wrong and the application server forwards to

/error

probably via a request dispatcher(?). I believe the request URI in this
case should be /bla/bla/bla and not /error -- is this what's confusing
things?

So, should I stick with my error servlet? If so what's the best way to
utilize Jersey to handle the request -- parse the Accept header myself and
get a MessageBodyWriter from MessageBodyWorkers?

Thanks,

jOrGe W.