users@jersey.java.net

[Jersey] more elegant exception mapping

From: Christopher Piggott <cpiggott_at_gmail.com>
Date: Wed, 12 Jan 2011 19:55:32 -0500

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