What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

ajax, exception, jsf-2

Solution

You need to implement a custom `ExceptionHandler` for this which does basically the following when an exception occurs in an ajax request:

String errorPageLocation = "/WEB-INF/errorpages/500.xhtml";
context.setViewRoot(context.getApplication().getViewHandler().createView(context, errorPageLocation));
context.getPartialViewContext().setRenderAll(true);
context.renderResponse();

This is not exactly trivial if you want to take `web.xml` error pages into account. You'd need to parse the entire `web.xml` for this to find the error page locations. Also, when the exception occurred during render response, then you'd basically need to rebuild the whole view yourself. The OmniFaces component library has exactly such an exception handler, the `FullAjaxExceptionHandler`. You can find the full source code here and the showcase example here.

See also:

- using ExternalContext.dispatch in JSF error handler causes corrupt page rendering

- Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

Problem

I have set up web.xml so that anything that's java.lang.Throwable (i.e. any uncaught exceptions or errors) will forward to an error page. However, for AJAXified components, exceptions dont get routed to the error page via this mechanism. The test case I have is a simple `CommandButton` tied to an action method that always throws a `RuntimeException`. It seems like the best practice would be to have the action method catch the exception and add a `FacesMessage` of type error severity. Is this what people do? Is there a way to configure JSF so that if an AJAXified component's backing bean method throws an exception that the error page can be shown?

Original source

Related problems