tags:

views:

541

answers:

2

How do you serialize a subclass of Exception?

Here is my exception:

@XmlType
public static class ValidationFault extends Exception {
 public ValidationFault() {

 }
}

I have tried all sorts of variations on using @XmlTransient and @XmlAccessorType, but JAXB continually tries to serialize the getStackTrace/setStackTrace pair, which can't be done.

How do I tell JAXB to ignore all the fields on the parent?

A: 

You could use an XmlAdapter to handle the marshalling/unmarshalling yourself. Something like this:

@XmlRootElement
public class JaxbWithException {

  public ValidationFault fault = new ValidationFault("Foo");

  @XmlJavaTypeAdapter(value = ValidationFaultAdapter.class)
  public static class ValidationFault extends Exception {
    public ValidationFault(String msg) {
      super(msg);
    }
  }

  public static class ValidationFaultAdapter extends
      XmlAdapter<String, ValidationFault> {
    @Override
    public String marshal(ValidationFault v) throws Exception {
      return v == null ? null : v.getMessage();
    }

    @Override
    public ValidationFault unmarshal(String v) throws Exception {
      return v == null ? null : new ValidationFault(v);
    }
  }

  public static void main(String[] args) {
    JAXB.marshal(new JaxbWithException(), System.out);
  }
}
McDowell
i want to serialize an exception, not a wrapper around an exception. Removing the wrapper leaves you with something that throws marshall/unmarshall errors.
Hamlet D'Arcy
+1  A: 

I solved this with the information at: http://forums.java.net/jive/thread.jspa?messageID=256122

You need to initialize your JAXBContext with the following config (where jaxbObj is the object to serialize):

Map<String, Object> jaxbConfig = new HashMap<String, Object>(); 
// initialize our custom reader
TransientAnnotationReader reader = new TransientAnnotationReader();
try {
 reader.addTransientField(Throwable.class.getDeclaredField("stackTrace"));
 reader.addTransientMethod(Throwable.class.getDeclaredMethod("getStackTrace"));
} catch (SecurityException e) {
 throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
 throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
 throw new RuntimeException(e);
}
jaxbConfig.put(JAXBRIContext.ANNOTATION_READER, reader); 

JAXBContext jc = JAXBContext.newInstance(new Class[] {jaxbObj.getClass()},jaxbConfig);
HappyEngineer
One issue with this solution is that when I compile and run it inside eclipse it works great. But if I try to compile it with maven then I get error messages like: package com.sun.xml.internal.bind.v2.model.annotation does not existI'm not sure what to do about that because that package is supposed to be part of the JDK.
HappyEngineer