users@jersey.java.net

[Jersey] Re: more elegant exception mapping

From: Paul Sandoz <Paul.Sandoz_at_oracle.com>
Date: Thu, 13 Jan 2011 10:16:06 +0100

Hi Christopher,

Some random thoughts:

- perhaps you can serialize out to JSON using Jackson. It may able to
handle things better.

- alternatively it might be possible to use MOXy JAXB instead (which
has more configuration options) or say XStream which is very flexible.

- write your own MessageBodyReader/Writer classes for the reading/
writing of Exception.

I would presume that exceptions can get serialized correctly using say
RMI, so there is probably a way to serialize the stack trace correctly
in textual form.

A word of caution. On the client side what it is really managing is
the reading of a remote exception. So it is not really the same
exception as expressed on the server-side and means something
different if re-thrown of the client side.

Paul.

On Jan 13, 2011, at 1:55 AM, Christopher Piggott wrote:

> Hi,
>
> I have been trying to find a more elegant way to deal with some
> exceptions I have created.
>
> public class AppBaseException extends Exception { }
> public class SpecificException extends AppBaseException { }
>
> My resource class normally returns a bean, but it might throw
> SpecificException if something goes wrong.
>
> The way I handle this now is :
>
> public class SpecificAppExceptionMapper extends
> ExceptionMapper<SpecificAppException> { }
>
> which, on map, throws another object I created:
>
> public class SpecificExceptionWrapper { }
>
> which does NOT extend Exception.
>
> On the client end, I've got something like:
>
> try {
> Something = response.getEntity(Something.class)
> } catch (UniformInterfaceException ex) {
> if( status == statusImInterestedIn ) {
> SpecificExceptionWrapper w =
> ex.getResponse().getEntity(SpecificExceptionWrapper.class);
> /* turn this into a SpecificException then throw it */
> }
> }
>
>
> If there's a bunch of representations for various statuses this gets
> pretty messy.
>
>
> What I would LIKE to do is to have the exception mapper just throw the
> exception and have one generic ExceptionMapper<AppBaseException> on
> the server side to serialize the exception directly, and take
> advantage of the fact that jaxb supports polymorphism via the root
> entity's name (provided I set up a JAXBContext to accomodate this).
>
> I can't do that, because anything that extends Exception can't be
> easily serialized by jaxb. I looked into tricks to do it, but they're
> all messy. (The real guts of the problem is that @XmlAccessorType
> doesn't override the default in java.lang.Exception -- meaning that
> jaxb always tries to serialize stackTrace and blows up. I even tried
> overriding getStackTrace() to no avail.)
>
>
> Any thoughts on how to better handle this sort of thing?
>
> --Chris