Re: [Jersey] exception handling best practices

From: Craig McClanahan <>
Date: Mon, 22 Feb 2010 12:02:59 -0800

On Mon, Feb 22, 2010 at 8:54 AM, Florian Hehlen <> wrote:
> Hi,
> I am wondering if there is a recommended way to map exceptions with jax-rs/jersey. I have been playing around with all the different exceptions that extend WebApplicationException, I have in some cases just pushed runtime exceptions back to the framework, and I have also considered using the ExceptionMapper interface. I realize that I could extend WebApplicationException to create my own exceptions aswell, but is that wise?
> - I would like to have the most consistent relationship between application exceptions/errors and HTTP codes.
> - I would also like to guarantee that a human readable message and a stacktrace travel with all my errors back to the client. Yet it seems that this happens with certain types of exceptions but not with others.
> -I would also like to spend the least amount of time/energy on maintaining all these different possible states.
> Is there one approach that's better than others? I can't at first glance see one. Am I missing something? Does anyone have any recommendations experiences?

My favorite approach is to create exception classes (extending
RuntimeException or WebApplicationException) that correspond to
various error conditions, then use ExceptionMapper to map them to an
appropriate status code with an appropriately formatted message (with
an appropriate media type). With these, I can tell a developer
writing a GET method in a resource class, that when the user tries to
access a resource that doesn't exist, just "throw
NotFoundException(...)" and let Jersey take care of remembering that
this should be a 404 with the correct media type and message format.
I find that this approach helps tremendously on getting consistently
formatted error messages, with the correct status code, even from a
developer that might be new to web services and doesn't have the
entire HTTP status code list memorized.

Regarding stack traces, I tend to be pretty cautious about including
them in responses to *external* users, because there is lots of
information there that might be used by a potential attacker. This
isn't such a big deal for internal-only apps.

> Cheers,
> Florian

Craig McClanahan