<错误页> web.xml中的标记不会捕获java.lang.Throwable异常 [英] <error-page> tag in web.xml doesn't catch java.lang.Throwable Exceptions

查看:157
本文介绍了<错误页> web.xml中的标记不会捕获java.lang.Throwable异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用servlet& amp; JSP。如果我插入错误的参数,我将我的应用配置为抛出 IllegalArgumentException
然后我以这种方式配置了我的web.xml文件:

I have a web-app developed with servlet & JSP. I configured my app to throw an IllegalArgumentException if I insert bad parameters. Then I configured my web.xml file in this way:

<error-page>
    <error-code>404</error-code>
    <location>/error.jsp</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error.jsp</location>
</error-page>

当我出现 404错误时,则它工作并调用 error.jsp ,但是当我提出 java.lang.IllegalArgumentException 时,它就不起作用了我有空白页而不是 error.jsp 。为什么?

When I rise a 404 error, then it works and calls error.jsp, but when I rise a java.lang.IllegalArgumentException, then it does not work and I've a blank page instead of error.jsp. Why?

服务器是Glassfish,日志显示IllegalArgumentException上升。

The server is Glassfish, and logs show really IllegalArgumentException rised.

推荐答案

你不应该抓住并压制它,但只是放手。

You should not catch and suppress it, but just let it go.

即不要这样做:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        doSomethingWhichMayThrowException();
    } catch (IllegalArgumentException e) {
        e.printStackTrace(); // Or something else which totally suppresses the exception.
    }
}

而是放手吧:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doSomethingWhichMayThrowException();
}

或者,如果你真的想抓住它进行伐木等等(我' d而是使用过滤器,但ala),然后重新抛出它:

Or, if you actually intented to catch it for logging or so (I'd rather use a filter for that, but ala), then rethrow it:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        doSomethingWhichMayThrowException();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw e;
    }
}

或者,如果它不是运行时异常,则重新抛出它包装在 ServletException 中,它将被容器自动解包:

Or, if it's not an runtime exception, then rethrow it wrapped in ServletException, it will be automatically unwrapped by the container:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        doSomethingWhichMayThrowException();
    } catch (NotARuntimeException e) {
        throw new ServletException(e);
    }
}



参见:



查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆