开发者

How to catch a nested exception in java

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(Transfo开发者_Python百科rmerImpl.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?


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


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.


Use Like this. it's working fine.

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

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜