JAXB XMLAdapter method does not throws Exception

余生颓废 提交于 2019-11-29 16:59:25

问题


I am using JAXB XMLadapter to marshal and unmarshal Boolean values. The application's XML file will be accessed by C# application also. We have to validate this XML file and this is done using XSD. C# application writes "True" value for Boolean nodes. But the same does get validated by our XSD as it only allows "true/false" or "1/0". So we have kept String for boolean values in XSD and that string will be validated by XMLAdapter to marshal and unmarshal on our side. The XML Adapter is as follows:

public class BooleanAdapter extends XmlAdapter<String, Boolean> {

    @Override
    public Boolean unmarshal(String v) throws Exception {

        if(v.equalsIgnoreCase("true") || v.equals("1")) {
            return true;
        } else if(v.equalsIgnoreCase("false") || v.equals("0")) {
            return false;
        } else {
            throw new Exception("Boolean Value from XML File is Wrong.");
        }
    }

    @Override
    public String marshal(Boolean v) throws Exception {
        return v.toString();        
    }
}

The code above works in normal conditions, but when invalid data(eg: "abcd" or "") is read from xml file then the "throw new Exception();" is not getting propagated and the Unmarshal process moves on to read next node. I want the application to stop as soon as an exception is thrown. It seems my Exception is getting eaten away. Any help is much appreciated.

How to resolve this problem?


回答1:


From the JavaDoc of XMLAdapter#unmarshal(ValueType):

Throws: java.lang.Exception - if there's an error during the conversion. The caller is responsible for reporting the error to the user through ValidationEventHandler.

So, yes - the exception is eaten and then reported using ValidationEventHandler, not thrown to the top of your stack.

Check if you are already using any (custom, perhaps) ValidationEventHandler that groups your exceptions, or use DefaultValidationEventHandler, like this:

unmarshaller.setEventHandler(new DefaultValidationEventHandler());

It will cause unmarshalling failure on first error.



来源:https://stackoverflow.com/questions/11114428/jaxb-xmladapter-method-does-not-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!