错误处理程序Servlet:如何获取异常原因

blu*_*oot 12 java servlets exception-handling

我在web.xml中配置了一个错误的servlet:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/ExceptionHandler</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

对?

在我的(通用)servlet中:

doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        ...
        ...
    } catch (Exception e) {
        throw new ServletException("some mesage", e);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,"e"将是这种情况下的根本原因.

在我的ExceptionHandler类中,我有:

doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
    throwable.getCause() //NULL
}
Run Code Online (Sandbox Code Playgroud)

这就是问题.throwable.getCause()为null.

Bal*_*usC 21

如果由servletcontainer捕捉到的异常是ServletException<error-page>声明捕捉异常其他ServletException,那么它的原因实际上将被解开,并为存储"javax.servlet.error.exception".所以你基本上已经把它作为throwable变量,你不需要调用getCause()它.

另请参见Servlet 2.5规范第9.9.2节的第5段:

如果没有使用类层次结构匹配的error-page包含exception-type拟合的声明,并且抛出的异常是其ServletException子类或子类,则容器将提取ServletException.getRootCause方法定义 的包装异常.对错误页面声明进行第二次传递,再次尝试匹配错误页面声明,但改为使用包装的异常.

顺便说一下,最好使用RequestDispatcher#ERROR_EXCEPTION常量而不是硬编码.

Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
Run Code Online (Sandbox Code Playgroud)