How to handle ClientAbortException in Spring-MVC?
I've had the same problem and i was unable to do what you tell with Spring MVC and a Exception handler. Some exceptions (Unchecked ones i guess) are not chatched by Spring MVC handlers. What i did was to define a generic filter in web.xml
<!-- Filter for exception handling, for those exceptions don't catched by Spring MVC -->
<filter>
<filter-name>LoggerFilter</filter-name>
<filter-class>com.myproject.commons.filters.ExceptionLoggerServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And the source of my filter:
public class ExceptionLoggerServletFilter implements Filter {
private static Log log = LogFactory.getLog(ExceptionLoggerServletFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
try {
chain.doFilter(request, response);
} catch (Throwable e) {
StringBuilder sb = new StringBuilder();
sb.append("Exception detected in ExceptionLoggerServletFilter:");
if (e instanceof org.apache.catalina.connector.ClientAbortException) {
// don't do full log of this error
sb.append(" ClientAbortException");
log.error(sb.toString());
} else {
log.error(sb.toString(), e);
}
throw e;
}
}
@Override
public void destroy() {
}
}
Since at least Spring Boot 2.3.4 (and probably before) you can use a @ControllerAdvice
annotated class with the following method:
@ExceptionHandler(ClientAbortException.class)
public void handleLockException(ClientAbortException exception, HttpServletRequest request) {
final String message = "ClientAbortException generated by request {} {} from remote address {} with X-FORWARDED-FOR {}";
final String headerXFF = request.getHeader("X-FORWARDED-FOR");
log.warn(message, request.getMethod(), request.getRequestURL(), request.getRemoteAddr(), headerXFF);
}