I want to catch and ignore the following tomcat ClientAbortException.
As it is unnecessary to pay any attention on this for my program.
Any idea how and
ClientAbortException extends IOException. You can try the code below to catch the exception:
try {
// codes
out.write("xyz"); // throws IOException
} catch (org.apache.catalina.connector.ClientAbortException ca) {
System.out.println("ClientAbortException caught");
} catch (IOException ioe) {
System.out.println("i/o exception raised. abrorting.");
}
In Spring 4, you would put this in a class annotated with @ControllerAdvice. The trick is to only suppress ClientAbortException while allowing every other IOException to be handled as errors or logged, without introducing a compile/runtime dependency on your container API:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
//import org.apache.catalina.connector.ClientAbortException; // We don't want this dependency.
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
@ControllerAdvice
public final class ErrorController
{
@ExceptionHandler(NoHandlerFoundException.class)
public String handleNoHandlerFoundException(final NoHandlerFoundException ex)
{
return "notFoundPage";
}
@ExceptionHandler(IOException.class)
public String handleAbortedConnection(final IOException ex)
{
// avoids compile/runtime dependency by using class name
if (ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException"))
{
return null;
}
// log and return error page for any other IOExceptions
if (LOGGER.isLoggable(Level.WARNING))
{
LOGGER.log(Level.WARNING, "IO Error", ex);
}
return "errorPage";
}
@ExceptionHandler(Exception.class)
public String handleException(final Exception ex)
{
if (LOGGER.isLoggable(Level.SEVERE))
{
LOGGER.log(Level.SEVERE, "Server Error", ex);
}
return "errorPage";
}
}
Thanks to this answer for providing the missing piece where we return null for the view name to avoid throwing a SocketException on the closed OutputStream.
since you probably don't want a dependency to Catalina, you can ignore the Exception like this (I'm assuming the ClientAbortException is the cause):
String simpleName = e.getCause().getClass().getSimpleName();
if (simpleName.equals("ClientAbortException")) {
// ignore
} else {
// do whatever you do
}