Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to handle Java exceptions in ServletContextListener

Tags:

For servlet lifecycle stuff, what do you guys recommend doing in response to an exception...

For example,

public class Foo implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        try {
           // something nasty
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        try {
           // something nasty
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

I'm not entirely sure what will handle the runtime exception above. I'm working from the idea that if exceptions are thrown here, they're serious enough to break the system completely so an (unhandled) runtime exception may be ok.

I guess I'm asking what handles unchecked exceptions from servlet context listeners?

like image 905
Toby Avatar asked Oct 27 '10 08:10

Toby


2 Answers

When you catch an exception, you might want to consider setting a ServletContext attribute to indicate that an error has been encountered. That way, if the container has not disabled the app, you can have Filters and/or Servlets inspect the ServletContext attribute and take appropriate action, like displaying an error page.

like image 60
kschneid Avatar answered Nov 03 '22 05:11

kschneid


It seems that ServletContentListener is not designed to be able to exercise control over the lifecycle (otherwise it would be allowed to throw a ServletException).

As such, I would not rely on a RuntimeException to do anything useful. Looking at some other threads here, it seems to be logged and ignored on certain application servers.

If it is critical that the application does not start when your code fails, you should move that code into a Servlet's initialization section.

like image 41
Thilo Avatar answered Nov 03 '22 05:11

Thilo