tags:

views:

27

answers:

2

This may be too ambiguous of a question, but I'm looking for some help or best practices on handling exceptions in a JavaServer Faces application.

Right now, whenever I catch an exception, I log it and then throw another exception that I created, say MyCustomException. This custom exception takes the Throwable object that was caught and emails the stack trace to me so that I know an exception has occurred. For now, this seems to work for me as far as being notified when an exception occurs.

However, the trouble that I'm having is how to present the user with a pretty error page that lets them know that something went wrong and that I have been notified of the error. Doing some searching, I've come across several articles that show how to redirect a user to another page using something similar to the following:

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();

String url = extContext.encodeActionURL(extContext.getRequestContextPath() +
    "/messages.faces");

extContext.redirect(url);

But this seems to be quite a bit to basically copy and paste for each caught exception, which doesn't exactly follow the DRY principle. In the end, I think what I would like to do is have an email sent to me whenever an exception occurs and then be able to send a message to a generic error page that then displays the message to the user.

Any ideas or best practices that I should follow? Thank you in advance for any advice you can give! I'm stumped.

Note: If it helps, I'm using JSF 2.0 and Facelets.

A: 

You'll want to use something like a servlet filter to catch (and handle) the exception. That way, there is only one global catch block :-)

That is, you would map a filter around the FacesServlet which does:

try {
    chain.proceed(request, response);
} catch (Exception e) {
    // handle the exception
}

Your JSF implementation might also have the notion of an error page. If it does, you might have to disable the error page so that exception reaches the filter.

You may find http://javaboutique.internet.com/tutorials/Servlet_Filters/ helpful.

meriton
+2  A: 

This urls could be useful for you:

http://weblogs.java.net/blog/edburns/archive/2009/09/03/dealing-gracefully-viewexpiredexception-jsf2

http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/

http://download.oracle.com/docs/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/api/javax/faces/context/ExceptionHandler.html

Basically you must use new feature in JSF2.0, ExceptionHandler. This is a central point for handling unexpected exception. You could indicate which page use for each exception type.

angelcervera