Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Zombies Avatar asked Aug 12 '09 15:08

Zombies


People also ask

How do you handle exceptions in Java Web application?

There are two main mechanisms of exception handling in Java Web Application: Programmatically exception handling mechanism: When using try and catch block in the Java code (Servlet or Filter class) to handle exceptions. Declarative exception handling mechanism: When using the XML tags in the web.

Can you catch all exceptions Java?

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block. An old, prior to Java 7 approach to handle multiple exceptions.

How do you catch all the exceptions?

We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

How do you you catch an exception in Java?

Catch Block In Java We use a catch block to handle exceptions. This is the block with the “catch” keyword. The catch block follows the try block. Whenever an exception occurs in the try block, then the code in the catch block that corresponds to the exception is executed.


1 Answers

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.

like image 71
Zombies Avatar answered Sep 28 '22 22:09

Zombies