2

我正在使用 Apache Xalan (v.2.7.1) 在 Apache Tomcat (v6.0.32) 中将 XML 转换为 XHTML。有时加载会被客户端取消并引发以下异常:

javax.xml.transform.TransformerException: org.apache.xalan.xsltc.TransletException: ClientAbortException:  java.io.IOException
    at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:636)
    at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:303)
...

我想捕获 ClientAbortException 异常,以便它不会向日志发送垃圾邮件。但是,如何检查异常是否嵌套在 ClientAbortException 中?我试过这样的事情:

...
} catch (Exception e) {
    if (e.getCause() != null && e.getCause().getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
        //do nothing
    } else {
        throw e;
    }
} finally {
...

但它只给了我一个空指针异常,因为第一个 getCause 没有 getCause。有任何想法吗?

4

3 回答 3

4

使用ExceptionUtils.getRootCause(Throwable)Apache Commons-lang 中的方法,它会为你遍历原因链。

于 2011-09-29T06:57:11.810 回答
1

如果getCause()返回 null,则javax.xml.transform.TransformerException实际上没有原因。创建异常时,您需要指定原因,而他们可能没有这样做。你可能对此无能为力。

您可以检查是否

一种方法可能是在 Exception@getMessage 上使用字符串匹配:

...
} catch (Exception e) {
    if (e.getMessage().contains("ClientAbortException:")) {
        // at least log the error, in case you've got something wrong
    } else {
        throw e;
    }
} finally {
...

但是,这可能不可靠,原因很明显,它取决于消息的文本。

编辑:考虑一下,您可能会发现在生产中捕获此异常是一个坏主意,或者您的代码错误,因此添加一个方法来打开或关闭此行为可能是一个好主意:

...
} catch (Exception e) {
    if (System.getProperty("abort.when.ClientAbortException") == null && e.getMessage().contains("ClientAbortException:")) {
        // at least log the error, in case you've got something wrong
...

然后,您至少可以选择关闭代码。System.getProperty 只是一个示例。

于 2011-09-29T07:05:10.373 回答
0

像这样使用。它工作正常。

catch (Exception e) {
if (e.getCause() != null && e.getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
    //do nothing
} else {
    throw e;
}

}

于 2021-03-08T05:55:24.817 回答