4

所以我使用过滤器来捕获 servlet 异常(因为我们使用的是 jsf/plain servlet 的混合)

当捕获 ServletException 并调用 printstacktrace 时,大部分信息都会丢失。

“真正的”根异常似乎隐藏在“有趣”的表达背后

((ServletException) e.getRootCause().getCause()).getRootCause().getCause().getCause().getCause()

这显然不是这样做的方法。

是打印此类异常的“完整”信息的简单方法。有人可以解释一下为什么以这种方式包装异常吗?

4

4 回答 4

6

查看 commons-lang 中的ExceptionUtils类。它包含几个有用的方法来打印整个异常链。

于 2009-05-19T14:29:39.743 回答
3

在我查看了 ExceptionUtils 之后,这解决了问题!

    final StringWriter stacktrace = new StringWriter();
    ExceptionUtils.printRootCauseStackTrace(throwable,new PrintWriter(stacktrace));
    msg.append(stacktrace.getBuffer());

这将打印出包含每条相关信息的完整堆栈跟踪。

于 2009-05-19T14:41:47.410 回答
1

这称为异常链接。通过将异常包装在不同的异常中,您可以让异常在堆栈中冒泡,而无需让您的主应用程序类担心一些低级异常。

例子:

public void doStuff() throws StuffException {
    try {
        doDatabaseStuff();
    } catch (DatabaseException de1) {
        throw new StuffException("Could not do stuff in the database.", de1);
    }
}

这样,您的应用程序只需要处理,但如果它真的需要,StuffException它可以到达底层。DatabaseException

要了解您捕获的异常的最底层(和所有其他)异常,您可以迭代其根本原因:

    ...
} catch (SomeException se1) {
    Throwable t = se1;
    logger.log(Level.WARNING, "Top exception", se1);
    while (t.getCause() != null) {
        t = t.getCause();
        logger.log(Level.WARNING, "Nested exception", t);
    }
    // now t contains the root cause
}
于 2009-05-19T14:20:32.210 回答
0

ServletException 的异常链接很棘手。根据使用的 Web 服务器实现和 Web 开发框架,在运行时链可能使用原因和/或 rootCause。这个链接很好地解释了它。使事情复杂化的是,我已经看到了原因指向异常本身的异常。这是我们使用的递归方法,它涵盖了 ServletExceptions 的所有基础:

public static Throwable getDeepCause(Throwable ex) {
    if (ex == null) {
        return ex;
    }
    Throwable cause;
    if (ex instanceof ServletException) {
        cause = ((ServletException) ex).getRootCause();
        if (cause == null) {
            cause = ex.getCause();
        }
    } else {
        cause = ex.getCause();
    }
    if (cause != null && cause != ex) {
        return getDeepCause(cause);
    } else {
        // stop condition - reached the end of the exception chain
        return ex;
    }
}
于 2015-08-24T18:32:45.890 回答