How to grab uncaught exceptions in a Java servlet web application

benstpierre picture benstpierre · Sep 14, 2011 · Viewed 7.3k times · Source

Is there a standard way to catch uncaught exceptions that happen inside of a java servlet container like tomcat or Jetty? We run a lot of servlets that come from libraries so we cannot easily put our on try/catch code. It would also be nice to in as generic of a way as possible catch and log all uncaught exceptions in our web application (which runs in Jetty) to our bug tracker via the API provided.

Please not I need to log the exceptions only, whether a a redirect is issues to a custom error page will not help me. We do everything via GWT-RPC so the user would never see an error page.

Answer

benstpierre picture benstpierre · Sep 14, 2011

I think a custom filter actually works best.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (Throwable e) {
        doCustomErrorLogging(e);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            //This should never be hit
            throw new RuntimeException("Unexpected Exception", e);
        }
    }
}