views:

160

answers:

1

Hi,

I am developing exception handling framework. The exception handling framework is for a JSF application.

The problem I am facing is tracking uncaught exception and displaying a generic message. I am able to handle uncaught exception for the action that are carried out(like on a click of a button), but I am not able to catch uncaught runtime exception at framework level while loading JSF pages or while initializing it. Any help will really be appreciated.

Thanks, Prasad

+1  A: 

That depends on how/where you're catching them. Normally, you'd like to specify an <error-page> in web.xml for that like so:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/error.html</location>
</error-page>

This basically shows the error.html page for any e instanceof java.lang.Exception.

Another way is to catch it in a Filter listening on an url-pattern of /*:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    try {
        chain.doFilter(request, response);
    } catch (Exception e) {
        request.setAttribute("exception", e);
        request.getRequestDispatcher("/error.html").forward(request, response);
    }
}

This does basically the same, you've only a bit more freedom in controlling the response and doing other stuff like logging.

Either way, it will fail whenever the response is already committed (i.e. the headers are already sent to the client side). You should then have noticed an IllegalStateException: response already committed in the server logs and the client will face a halfbaked (or even blank) page. This is a point of no return. You'd like to execute any business logic before rendering of the response. It's also one of the reasons that it's considered bad practice to do the business logic in the view (JSP/Facelets) side.

BalusC
Thanks for the response. At present, I have handlers to handle all uncaught exception and included it in the faces-config.xml<application> <action-listener>com.exception.listener.UncheckedExceptionListener</action-listener> </application>This takes care of all the uncaught exception when an action takes place, but this does not take care of onPAgeLoade or pre-rendered calls exception. Please let me know, how to handle this.
Nrusingha
I have no idea since I never used this approach to handle exceptions, but it makes sense to me that they are unhandleable. What would you like to do with them?
BalusC
Catch the exception and show the error message on the same page rather that navigating to a different page. The messages will be shown using <h:messages>
Nrusingha