简体   繁体   English

JAXB XMLAdapter方法不会抛出异常

[英]JAXB XMLAdapter method does not throws Exception

I am using JAXB XMLadapter to marshal and unmarshal Boolean values. 我正在使用JAXB XMLadapter来编组和解组布尔值。 The application's XML file will be accessed by C# application also. 应用程序的XML文件也将由C#应用程序访问。 We have to validate this XML file and this is done using XSD. 我们必须验证此XML文件,这是使用XSD完成的。 C# application writes "True" value for Boolean nodes. C#应用程序为布尔节点写入“True”值。 But the same does get validated by our XSD as it only allows "true/false" or "1/0". 但是我们的XSD也证实了这一点,因为它只允许“真/假”或“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. 因此,我们在XSD中保留了String的布尔值,XMLAdapter将验证该字符串,以便我们编组和解组。 The XML Adapter is as follows: XML Adapter如下:

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();" 上面的代码在正常情况下工作,但是当从xml文件中读取无效数据(例如:“abcd”或“”)时,则抛出“new new Exception();” is not getting propagated and the Unmarshal process moves on to read next node. 没有传播,Unmarshal进程继续读取下一个节点。 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? 如何解决这个问题?

From the JavaDoc of XMLAdapter#unmarshal(ValueType) : 来自XMLAdapter#unmarshal(ValueType)的JavaDoc:

Throws: java.lang.Exception - if there's an error during the conversion. 抛出: java.lang.Exception - 如果在转换过程中出现错误。 The caller is responsible for reporting the error to the user through ValidationEventHandler . 调用者负责通过ValidationEventHandler向用户报告错误

So, yes - the exception is eaten and then reported using ValidationEventHandler , not thrown to the top of your stack. 所以,是的 - 了异常然后使用ValidationEventHandler报告,而不是抛到堆栈的顶部。

Check if you are already using any (custom, perhaps) ValidationEventHandler that groups your exceptions, or use DefaultValidationEventHandler , like this: 检查您是否已经使用任何(自定义的) ValidationEventHandler对您的异常进行分组,或者使用DefaultValidationEventHandler ,如下所示:

unmarshaller.setEventHandler(new DefaultValidationEventHandler());

It will cause unmarshalling failure on first error. 它会在第一次错误时导致解组失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM