我有一个使用servlet& amp; JSP。如果我插入错误的参数,我将我的应用配置为抛出IllegalArgumentException
。
然后我以这种方式配置了我的web.xml文件:
<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
时,它会有效并调用error.jsp
,但是当我抬起java.lang.IllegalArgumentException
时,它就不起作用而且我有一个blank page
而不是error.jsp
。为什么呢?
服务器是Glassfish,日志显示IllegalArgumentException上升。
答案 0 :(得分:7)
你不应该抓住并压制它,但要放手。
即。不要这样做:
@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();
}
或者,如果你真的打算用它来记录它(我宁愿使用过滤器,但是ala),然后重新抛出它:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
doSomethingWhichMayThrowException();
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
或者,如果它不是运行时异常,则重新抛出它包裹在ServletException
中,它将被容器自动解包:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
doSomethingWhichMayThrowException();
} catch (NotARuntimeException e) {
throw new ServletException(e);
}
}
答案 1 :(得分:1)
另一种(简化的)方法不是为各种 <error-code>
和 <exception-type>
情况声明多个处理程序,而是有一个,一种包罗万象的接收器,例如
<error-page>
<location>/error-page.jsp</location>
</error-page>
在您的 error-page.jsp
中,您可以确定原因,无论是返回状态代码还是此处所述的异常:https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm 这些常量是标准 Servlet 3.0 API 的一部分。>
例如,放置在您的 web 应用程序根目录中的原始 error-page.jsp
响应处理程序可能如下所示:
Server encountered a situation
Status code: <%=(Integer) request.getAttribute(javax.servlet.RequestDispatcher.ERROR_STATUS_CODE)%>
<br>
Exception: <%=(Throwable) request.getAttribute(javax.servlet.RequestDispatcher.ERROR_EXCEPTION)%>
出于安全原因,我不建议向客户端发送确切的异常类型;这只是如何在 JSP
处理程序中处理不同类型的错误和响应状态的示例;可以使用 servlet 代替 JSP。
一个通用的包罗万象的处理程序与每个状态代码一个当然取决于具体情况和要求。
答案 2 :(得分:0)
我今天有同样的问题。 (JavaEE 7和Glassfish 4.0)
问题似乎是框架将其检查为String而不是Class。
当异常被抛出时,e.getClass()
将与<exception-type>
作为字符串进行比较。
所以你不能使用继承。
请注意,嵌套类必须指向“$”而不是“。” (与getClass()方法相同)。
框架创建了一个类的实例,<exception-type>
文本引用它,class.isInstance()
用于检查。
这需要反思,而政策文件可能会破坏它。
我希望这一回应可以解决未来的问题。