Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save songyunlu/6247349 to your computer and use it in GitHub Desktop.
Save songyunlu/6247349 to your computer and use it in GitHub Desktop.
package servletutils;
import com.google.common.base.Preconditions;
import javax.servlet.*;
import javax.servlet.http.*;
public class UnhandledExceptionFilter implements Filter {
public interface ErrorHandler {
void handle(HttpServletRequest request, HttpServletResponse response, Throwable throwable);
}
private ErrorHandler errorHandler;
public UnhandledExceptionFilter()
{ }
public UnhandledExceptionFilter(ErrorHandler errorHandler) {
Preconditions.checkNotNull(errorHandler);
this.errorHandler = errorHandler;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO: add init code to lookup errorHandler
}
// suppress calls to sendError() and just setStatus() instead
private static class StatusCodeCaptureWrapper extends HttpServletResponseWrapper {
public StatusCodeCaptureWrapper(HttpServletResponse response) {
super(response);
}
@Override
public void sendError(int sc) throws IOException {
// do NOT use sendError() otherwise per servlet spec the container will send an html error page
this.setStatus(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
// do NOT use sendError() otherwise per servlet spec the container will send an html error page
this.setStatus(sc, msg);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
StatusCodeCaptureWrapper responseWrapper = new StatusCodeCaptureWrapper(response);
Throwable throwable = null;
try
{
chain.doFilter(request, responseWrapper);
}
catch (ServletException e)
{
throwable = e.getRootCause();
}
catch (Throwable e)
{
throwable = e;
}
if (throwable != null)
{
errorHandler.handle(request, response, throwable);
}
// flush to prevent servletcontainer to add anymore headers or content
response.flushBuffer();
}
@Override
public void destroy() {
// noop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment