如何在Console上停止打印异常堆栈跟踪?

Sur*_*tta 19 java tomcat web.xml servlets socketexception

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

    <error-page>
      <exception-type>java.lang.Exception</exception-type>
      <location>/exceptionHandler</location>
    </error-page>
Run Code Online (Sandbox Code Playgroud)

这是我在异常处理servlet service方法中所做的:

@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);
         }
    }.
Run Code Online (Sandbox Code Playgroud)

问题:

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

题:

每当SocketException发生时,如何停止将printtrace打印到JBoss控制台?

这样做的原因:

我想避免SocketException在第一天结束时看到所有日志,因为我无法对这些信息做任何事情.

Sur*_*tta 7

这就是我在战争中所做的工作.

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

/**
 * 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.    
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

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>  
Run Code Online (Sandbox Code Playgroud)

我不是把它标记为答案,因为我不确定这是否是标准方法.只是一个解决方法.

  • 是的,我理解你想要实现的目标,它肯定会阻止日志散布着误导性的异常.您可以做的唯一"处理SocketException"的方法是将一条小消息写入用户中止请求的正常日志(可能在调试/信息级别).如果您在生产中遇到一些问题并且必须遵循日志文件,则可以更轻松地跟踪会话.我有这个规则记录进入或离开我的应用程序的所有内容,以便我可以跟踪事情. (3认同)

Pra*_*ash 7

不要java.lang.Exception在web.xml 中添加,为什么不尝试在web.xml本身中添加套接字异常,如下所示

<error-page>
  <exception-type>java.net.SocketException</exception-type>
  <location>/exceptionHandler</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

并且只是在你的servlet中什么都不做 或者改为添加一个空的jsp文件

<error-page>
  <exception-type>java.net.SocketException</exception-type>
  <location>/error.jsp</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)


Man*_*ikh 2

您可能必须重写 fillInStackTrade 方法

public static class CustomException extends Exception {
@Override
public Throwable fillInStackTrace() {
    return null;
}       
Run Code Online (Sandbox Code Playgroud)

}