Zombies
Zombies

Reputation: 25912

Catching every exception in Java EE web apps

First, I am throwing run time exceptions for all unrecoverable exceptions, this causes these exceptions to travel up to the container, where I currently use an error page (defined in web.xml). In this error page is a scriptlet that invokes the logger.

The issue I am having with this is that the exception is no longer on the stack at this invocation. I have access to it from a request scope variable ("javax.servlet.error.message"). This string is the stack trace. I need this stack trace for logging purposes obviously, and on different app servers "javax.error_message" can be turned off for security reasons.......

So my question is, how can best log runtime exceptions from within Java EE apps without wrapping everything in this:

try {} catch (Exception e) {logger.log(...)}

?

I want some way to invoke the logger from the container maybe... right before the container catches the exception for example.

Upvotes: 6

Views: 2102

Answers (4)

Zombies
Zombies

Reputation: 25912

I found a solution. By adding a response filter and wrapping chain.doFilter(req, resp) like so:

try {
    chain.doFilter(req,resp);
} catch (Exception e) {
    logger.error("", e);
    throw new RuntimeException(e);
}

This works fine so far and isn't dependent on a particular framework or app server.

Upvotes: 3

sourcerebels
sourcerebels

Reputation: 5190

AOP (Aspect Oriented Programming) would be my first choice.

You define:

  • join point (a runtime exception is thrown).
  • advice (your code to log the exception).
  • point cuts (which parts of your applications are "listening" this aspect).

Take a look at http://www.aspectj.org/

Upvotes: 0

Ryan Fernandes
Ryan Fernandes

Reputation: 8536

Correct me if I'm wrong, but the 'exception' object is present as a variable.. called 'exception' in your 'error' jsp. You could always use this object to log retrieve the exception information and log in in the error jsp itself.

Upvotes: 0

ZZ Coder
ZZ Coder

Reputation: 75496

There is nothing I know of in Servlet API to accomplish this.

However, you can do this in Tomcat with an instance listener. You can install a listener in context.xml like this,

<InstanceListener>myapp.MyListener</InstanceListener>

Tomcat fires InstanceEvent.AFTER_SERVICE_EVENT event right after the container catches the exception and before it throws the exception again. You can invoke the logger right there.

Upvotes: 1

Related Questions