views:

565

answers:

2

I am trying to figure out a clean way to intercept uncaught exceptions that occur in my application.

I have log4j configured for logging the normal application flow and caught exceptions, so that is taken care of. Right now, I have a class that takes all error-level messages and adds them to a queue to be emailed in batches.

Ideally, I'm hoping that there is a way I can go about intercepting the uncaught exceptions, so that I may pass them to the same 'email batch' queue, but if this is not posible, I'm certainly open to suggestion.

I'm familiar with LogInterceptors on JBoss, but this project is using Tomcat. Is there any way that I might go about this? Is there a LogInterceptor equivelant for Tomcat? Should I try to redirect the Tomcat logging to a custom appender? (If so - any hints on that?) Some other ideas?

I figured that this has to be a solved problem by now, so I am hoping to tap some collective wisdom. Thanks, everyone, in advance.

+1  A: 

Per the J2EE 1.4 spec, uncaught exceptions within a servlet may be forwarded to an error page as defined in the deployment descriptor. When this happens, the page implementation will receive the original request and response objects, with the addition of a request attribute named javax.servlet.error.exception that contains the exception object.

That said, I have not actually done this with Tomcat, and most of the web applications that I've worked on forward to a generic error page at the webserver level.

Edit: just tried it out on my local server, after adding the following to my web.xml, and it works as advertised:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/dumpRequest.jsp</location>
</error-page>
kdgregory
A: 

It's not Tomcat-specific, but you can set uncaught exception handlers on a per-thread basis.

Depending on the setup of your application, you could set this at the top of your method that handles a request. You might have to do it every time, as you may get a thread per request.

A good place to set it would be in some sort of front controller.

Dan Vinton
I guess this wont work as tomcat will be catching all the exceptions even if your app doesn't. If it don't threads in its threadpool will keep dying on webapp errors.
Tahir Akhtar