You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用javax.xml.validation.Validator验证XML时SAXException传播异常问题

XML验证方法的异常传播问题修复

原代码

public boolean validateXML() throws Exception {
    sepaRTLogger.info("Entered validateXML()");
    Schema schema = listOfXSDs.get(xmlVersion);
    sepaRTLogger.debug("matched schema:::" + schema);
    System.out.println("matched schema:::" + schema);
    
    try {
        Validator validator = schema.newValidator();
        validator.validate((Source) (new StreamSource(XMLStreamForValidation)));
    } catch (Exception e){
        if(e instanceof IOException) {
            sepaRTLogger.error("IOException error:",e);
        }
        if(e instanceof SAXException){
            sepaRTLogger.error("SAXException error:",e);
            retriggerException.reThrow(msgTagID, null, new SAXException(), e.getMessage(), "TFLT101");
        }
        throw new Exception( e);
    }finally{
        XMLStreamForValidation.close();
    }

    return true;
}

问题点

  • sepaRTLogger.error("SAXException error:",e);:该行可正常打印错误信息,原异常e的完整信息能被正确输出
  • retriggerException.reThrow(msgTagID, null, new SAXException(), e.getMessage(), "TFLT101");:该行传入了全新的SAXException实例,未关联原异常的上下文信息,导致后续无法正常传播原SAXException,甚至出现异常变为null的情况

原因分析

创建新SAXException时未将原异常作为异常原因传入,导致新实例丢失了原异常的栈轨迹、内部细节等关键上下文,reThrow方法无法基于有效异常实例完成传播逻辑。

修复方案

通过关联原异常上下文,让reThrow方法能正确处理并传播异常:

方案一:保留原异常完整上下文

将新创建的SAXException改为携带原异常的实例:

retriggerException.reThrow(msgTagID, null, new SAXException(e.getMessage(), e), e.getMessage(), "TFLT101");

方案二:直接传入原异常实例

若reThrow方法支持接收原SAXException实例,可直接传递原异常:

retriggerException.reThrow(msgTagID, null, e, e.getMessage(), "TFLT101");

两种方案都能保留原异常的完整信息,确保reThrow方法正常传播异常,避免出现异常为null的问题。

内容的提问来源于stack exchange,提问作者Kumar Umesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:45:03