如何在Java servlet Web应用程序中抓取未捕获的异常 [英] How to grab uncaught exceptions in a Java servlet web application

查看:2865
本文介绍了如何在Java servlet Web应用程序中抓取未捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种标准的方法可以捕获像tomcat或Jetty这样的java servlet容器中发生的未捕获的异常?我们运行了很多来自图书馆的servlet,所以我们不能轻易地把我们的try / catch代码。在我们的Web应用程序(运行在Jetty)中的所有未捕获的异常都可以通过提供的API捕获并记录到我们的错误跟踪器中。通常的方式可以通过API提供的方式捕获并记录所有未捕获的异常。



请不需要仅记录例外情况,重定向是否发生到自定义错误页面不会帮助我。我们通过GWT-RPC做所有事情,所以用户永远不会看到错误页面。

解决方案

我认为自定义过滤器实际上最有效

  @Override 
public void doFilter(ServletRequest请求,ServletResponse响应,FilterChain链)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 {
//这不应该被击中
抛出新的RuntimeException(意外异常,e);
}
}
}


Is there a standard way to catch uncaught exceptions that happen inside of a java servlet container like tomcat or Jetty? We run a lot of servlets that come from libraries so we cannot easily put our on try/catch code. It would also be nice to in as generic of a way as possible catch and log all uncaught exceptions in our web application (which runs in Jetty) to our bug tracker via the API provided.

Please not I need to log the exceptions only, whether a a redirect is issues to a custom error page will not help me. We do everything via GWT-RPC so the user would never see an error page.

解决方案

I think a custom filter actually works best.

@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);
        }
    }
}

这篇关于如何在Java servlet Web应用程序中抓取未捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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