有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在JavaServlet web应用程序中捕获未捕获的异常

有没有一种标准的方法来捕获发生在像tomcat或Jetty这样的Javaservlet容器中的未捕获异常?我们运行了很多来自库的servlet,所以我们不能轻易地将我们的代码放在try/catch上。最好能以尽可能通用的方式捕获web应用程序(在Jetty中运行)中所有未捕获的异常,并通过提供的API将其记录到bug跟踪器中

请不要,我只需要记录异常,是否重定向到自定义错误页对我没有帮助。我们通过GWT-RPC做所有事情,这样用户就不会看到错误页面


共 (3) 个答案

  1. # 1 楼答案

    我认为定制过滤器实际上效果最好

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Throwable e) {
            doCustomErrorLogging(e);
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof ServletException) {
                throw (ServletException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                //This should never be hit
                throw new RuntimeException("Unexpected Exception", e);
            }
        }
    }
    
  2. # 2 楼答案

    无法100%确定这是否适用于servlet容器,或者此调用需要向上游多远,但是您可以在Thread上调用staticsetDefaultUncaughtExceptionHandler方法来设置处理所有未捕获异常的处理程序

  3. # 3 楼答案

    web.xml(部署描述符)中,可以使用^{}元素按异常类型或HTTP response status code指定错误页。例如:

    <error-page>
        <error-code>404</error-code>
        <location>/error/404.html</location>
    </error-page>
    <error-page>
        <exception-type>com.example.PebkacException</exception-type>
        <location>/error/UserError.html</location>
    </error-page>
    

    对于以NetBeans为中心的描述,请在Configuring Web Applications: Mapping Errors to Error Screens (The Java EE 6 Tutorial)(或参见the Java EE 5 Tutorial's version)上搜索