<错误页> web.xml中的标记不会捕获java.lang.Throwable异常 [英] <error-page> tag in web.xml doesn't catch java.lang.Throwable Exceptions
问题描述
我有一个使用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);
}
}
参见:
- 服务器如何优先考虑使用哪种类型的web.xml错误页面?
- https://stackoverflow.com/questions/9739472/what-to-do -with-exceptions-why-and-when-do-doget-method-throw-servletexcept / 9746657#9746657
- How does server prioritize which type of web.xml error page to use?
- https://stackoverflow.com/questions/9739472/what-to-do-with-exceptions-why-and-when-does-doget-method-throw-servletexcept/9746657#9746657
See also:
这篇关于<错误页> web.xml中的标记不会捕获java.lang.Throwable异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!