How to catch a nested exception in java

大城市里の小女人 提交于 2019-12-12 20:28:16

问题


I'm using Apache Xalan (v.2.7.1) to translate XML to XHTML in Apache Tomcat (v6.0.32). Sometimes the loading gets cancelled by the client and the following exception is thrown:

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)
...

I would like to catch the ClientAbortException-exception, so that it doesn't spam the log. However, how can I check if the exception is nested inside the ClientAbortException? I tried something like this:

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

But it only gives me a nullpointerexception as the first getCause doesn't have a getCause. Any ideas?


回答1:


Use the ExceptionUtils.getRootCause(Throwable) method in Apache Commons-lang, it will traverse the cause chain for you.




回答2:


If getCause() is returning null, then the javax.xml.transform.TransformerException doesn't actually have a cause. When the Exception is created, you need to specify the cause, and they probably haven't done this. You probably can't do anything about that.

You can check if the

One method could just be to use a String match on 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 {
...

However, this may be unreliable, for the obvious reason that it depends upon the text of the message.

EDIT: Thinking about it, you may find out in production that catching this exception is a bad idea, or that you've got the code wrong, so adding a method to turn on or off this behaviour may be a good idea:

...
} 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
...

Then you at least have the option of turning off the code. The System.getProperty is just an example.



来源:https://stackoverflow.com/questions/7593535/how-to-catch-a-nested-exception-in-java

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