XmlJavaTypeAdapter Throw Custom Exception

Is there a way to throw a custom exception in the XmlAdapter and catch them when JAXB marshalles / unmarshalls? I mean, I can throw my own exception, but JAXB just ignores this exception and throws it from which I cannot get to my exception message or exception object.

try {
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    jaxbUnmarshaller.unmarshal(inputStream);
}
catch (UserDefinedException e) {
    // Do something.
}

Sorry for not posting the correct exception that JAXB chose instead of mine. At the moment I can not get to the code. Currentlly I use JAXB-RI, but I used EclipseLink MoXY and ran into this problem.

I will post additional data when I can get a hand from the code. But until then, maybe someone knows what I'm talking about. Some sample code for using XmlAdapter correctly is also good.

Thank.

+3
source share
1 answer

The expectation of JAXB (JSR-222) is that it throws JAXBException. This means that any exceptions made inside something like XmlAdapterwill be completed. You can use stateful XmlAdapterto handle this use case:

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyXmlAdpater myXmlAdapter = new MyXmlAdapter();
jaxbUnmarshaller.setAdatper(myXmlAdapter);
jaxbUnmarshaller.unmarshal(inputStream);
if(myXmlAdapter.hasException() {
    // Do something.
}

XmlAdapterSee an example of using a state below:

+1
source

All Articles