如何停止在控制台上打印异常堆栈跟踪?

2024-04-27

我编写了一个 Servlet 来处理 Web 应用程序中发生的异常,并将它们映射到 web.xml 中

    <error-page>
      <exception-type>java.lang.Exception</exception-type>
      <location>/exceptionHandler</location>
    </error-page>

这是我在异常处理 servlet 中所做的事情service method:

@Override
    protected void service(HttpServletRequest req, HttpServletResponse arg1)
            throws ServletException, IOException {
         Object attribute = req.getAttribute("javax.servlet.error.exception");
         if(attribute instanceof  SocketException){
            // don't do anything 
         }else{
          super.service(req, arg1);
         }
    }.

Problem:

上述方法不起作用,堆栈跟踪正在打印到控制台。当用户请求某些内容然后关闭浏览器时,就会发生这种情况。

问题:

每当出现以下情况时,如何停止将堆栈跟踪打印到 JBoss 控制台SocketException occurs?

这样做的原因:

我想避免看到所有日志SocketException这是在当天结束时,因为我无法利用该信息做任何事情。


这就是我所做的,所以战争作为解决办法。

添加一个过滤器,劫持所有请求和响应。捕获异常并检查类型。

/**
 * Hijacks all the http request and response here.
 * Catch the SocketException and do not print 
 * If other exceptions print to console
 * date : 9-18-2013
 * 
 * @author Suresh Atta
 *
 */
public class ExceptionHandler implements Filter {

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        try{
        arg2.doFilter(arg0, arg1);
        }catch(SocketException e ){
           // Please don't print this to log.    
        }
    }


}

And in web.xml,过滤器映射

<filter>
        <filter-name>ExceptionHandler</filter-name>
        <filter-class>com.nextenders.server.ExceptionHandler</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ExceptionHandler</filter-name>
        <dispatcher>  REQUEST   </dispatcher>
        <url-pattern> /*</url-pattern>
    </filter-mapping>  

我不会将此标记为答案,因为我不确定这是否是标准方法。只是一种解决方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何停止在控制台上打印异常堆栈跟踪? 的相关文章

随机推荐