Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlJavaTypeAdapter throw user defined exception

Tags:

jaxb

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

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

Sorry for not posting the correct exception that JAXB throwed instead of mine. At this moment, I can not get to the code. Currentlly I am using JAXB-RI, but I used EclipseLink MoXY and encountered this problem.

I will post additional data when I am able to get the hand of the code. But till then, maybe someone knows what am I talking about. Some code example of correct usage of XmlAdapter is also great.

Thanks.

like image 599
Hrvoje Varga Avatar asked Jun 28 '26 08:06

Hrvoje Varga


1 Answers

The expectation of a JAXB (JSR-222) implementation is that it throws a JAXBException. This means that any exceptions thrown within something like an XmlAdapter is going to end up getting wrapped. You could potentially use a stateful XmlAdapter to handle this use case:

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

For an Example of using a stateful XmlAdapter see:

  • http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html
like image 54
bdoughan Avatar answered Jun 30 '26 18:06

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!