20

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

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

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

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

问题:

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

问题:

每当发生 a 时,如何停止将堆栈跟踪打印到 JBoss 控制台SocketException

这样做的原因:

我想避免SocketException在一天结束时看到所有日志,因为我对这些信息无能为力。

4

7 回答 7

7

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

<error-page>
  <exception-type>java.net.SocketException</exception-type>
  <location>/exceptionHandler</location>
</error-page>

并且在您的 servlet 中什么也不做, 或者添加一个空的 jsp 文件,例如

<error-page>
  <exception-type>java.net.SocketException</exception-type>
  <location>/error.jsp</location>
</error-page>
于 2014-03-10T07:43:21.983 回答
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.    
        }
    }


}

而在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>  

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

于 2013-09-19T05:19:50.010 回答
3

Use Jboss Custom Logging Handler to solve this problem.

If you don't want to log any SocketException exception stack trace then just skip it while loggin into a file.

Steps to follow:

  • A custom handler must inherit java.util.logging.Handler

Here is the code:

package com.custom.jboss.logging;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.logging.ErrorManager;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class SocketExceptionCustomLoggingHandler extends Handler {

    private String logFile;
    public BufferedWriter out = null;

    public SocketExceptionCustomLoggingHandler() {
        super();
        logFile = "";
    }

    @Override
    public void publish(LogRecord record) {
        if (!initialize()) {
            return;
        }
        if (isLoggable(record)) {
            process(record);
        }
    }

    private synchronized boolean initialize() {
        if (out == null && logFile != null && !logFile.equals("")) {
            FileWriter fstream = null;
            try {
                fstream = new FileWriter(logFile, true);
                out = new BufferedWriter(fstream);
            } catch (IOException e) {
                reportError(e.getMessage(), e, ErrorManager.OPEN_FAILURE);
            }
            logToFile("Log file initialized. Logging to: " + logFile);
        }
        return true;
    }

    private void process(LogRecord logRecord) {

        String log = getFormatter().format(logRecord);
        if (log.indexOf("java.net.SocketException") == -1) {
            logToFile(log);
        }
    }

    private void logToFile(String text) {
        try {
            if (out != null) {
                out.write((new Date()).toString() + "\t" + text + "\n");
                out.flush();
            }
        } catch (IOException e) {
            reportError(e.getMessage(), e, ErrorManager.WRITE_FAILURE);
        }

    }

    @Override
    public void flush() {
        try {
            if (out != null) {
                out.flush();
            }
        } catch (IOException e) {
            reportError(e.getMessage(), e, ErrorManager.FLUSH_FAILURE);
        }
    }

    @Override
    public void close() {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                reportError(e.getMessage(), e, ErrorManager.CLOSE_FAILURE);
            }

        }
    }

    public void setLogFile(String logFile) {
        this.logFile = logFile;
    }

}
  • The file is then packaged into a jar and placed in the modules directory.

    i.e. Jboss-7.1.1/modules/com/custom/jboss/loggers/main together with a module.xml file. The contents of the module.xml should look like this.

    <?xml version="1.0" encoding="UTF-8"?>   
    <module xmlns="urn:jboss:module:1.0" name="com.custom.jboss.loggers">  
         <resources>      
               <resource-root path="SocketExceptionHandler.jar"/>  
              <!-- Insert resources here -->   
         </resources>    
         <dependencies>      
              <module name="org.jboss.logging"/>  
              <module name="javax.api"/>   
         </dependencies>  
    </module>  
    
  • Then modify the standalone.xml to support logging to the custom logger

    <subsystem xmlns="urn:jboss:domain:logging:1.1">
        ...
        <custom-handler name="SocketExceptionAppender" class="com.custom.jboss.logging.SocketExceptionCustomLoggingHandler" module="com.custom.jboss.loggers">
            <level name="DEBUG"/>
            <formatter>
                <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
            </formatter>
            <properties>
                <property name="logFile" value="d:\\temp\\logfile.txt"/>
            </properties>
        </custom-handler>
        ...
        <root-logger>
            <level name="INFO"/>
            <handlers>
                <handler name="SocketExceptionAppender"/>                    
            </handlers>
        </root-logger>
    </subsystem>
    
  • Add more handler in root-logger if needed such as FILE, CONSOLE etc.

  • Now all the logs will be logged in your custom log file via this custom handler where we have skipped SocketException
  • We can make this class more generic passing properties from standalone.xml such as used to pass log file path.

Please let me know if there is any issue.

于 2014-03-10T23:46:14.590 回答
2

您可能必须重写 fillInStackTrade 方法

public static class CustomException extends Exception {
@Override
public Throwable fillInStackTrace() {
    return null;
}       

}

于 2013-09-17T12:18:31.363 回答
2

据我了解,如果在到达容器之前未捕获异常,则会将异常记录到控制台。因此,使用过滤器来捕获未处理的异常是有意义的。

默认情况下,Struts2 也有一个异常 'interceptor' 作为它的最后一个拦截器。请参阅默认堆栈。如果我们需要自定义异常处理,我们需要覆盖这个拦截器。

我唯一要做的就是记录异常(至少到一个errors-ignore.txt文件),而不是完全跳过它们。

于 2013-11-04T18:09:02.167 回答
1

Another funky idea: you could create exception handler

class SocketExceptionSwallower implements Thread.UncaughtExceptionHandler {
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof SocketException) {
                // swallow
            } else {
                e.printStackTrace();
            }
        }
    }

and registered with

Thread.setDefaultUncaughtExceptionHandler(new SocketExceptionSwallower());

or

Thread.currentThread().setUncaughtExceptionHandler(new SocketExceptionSwallower());

Simple, no overhead of another filter in chain, but it messes with threads and will probably break something in Java EE environment )
Might be useful in testing/experimenting or if you fully control threads in your own code

于 2014-03-13T15:23:35.833 回答
1

您可以使用Logger. 为此,您需要log4j库并将所有所需的行为和异常写入日志文件。为此,您需要提供日志文件路径

于 2014-03-14T05:25:19.533 回答