How to stop printing exception stack trace on Console?

Suresh Atta picture Suresh Atta · Sep 17, 2013 · Viewed 15k times · Source

I wrote a servlet to handle the exceptions occurring in my web app and mapped them in web.xml

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

Here is what I have done in the Exception Handling 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:

The above approach is not working and the stack trace is printing to the console. This occurs when the user requests something and then closes their browser.

Question:

How do I stop printing the stacktrace to the JBoss console whenever a SocketException occurs?

Reason for doing this:

I want to avoid seeing all of the log's SocketExceptions at the end of th day because I can't do anything with that information.

Answer

Suresh Atta picture Suresh Atta · Sep 19, 2013

Here is what I done so war as work around.

Added one filter and hijack all the request and response.Catch the exception and check the type.

/**
 * 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 mapping

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

I'm not marking this as answer,since I'm not sure this is a standard way or not.Just a work around.