JSF 1.x generic exception handling

gaurav picture gaurav · Jan 20, 2009 · Viewed 38k times · Source

If I have an exception in my business layer (e.g. a SQL exception in my JDBC connection bean), how can I propagate it with a custom message to a global error.jsp page?

Answer

McDowell picture McDowell · Jan 20, 2009

JSF 1.x doesn't provide any implicit error handling of this type, though you can redirect to an error page using navigation rules (assuming a form post)...

<navigation-case>
<description>
Handle a generic error outcome that might be returned
by any application Action.
</description>
<display-name>Generic Error Outcome</display-name>
<from-outcome>loginRequired</from-outcome>
<to-view-id>/must-login-first.jsp</to-view-id>
</navigation-case>

...or using a redirect...

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String url = extContext.encodeActionURL(extContext
        .getRequestContextPath()
        + "/messages.faces");
extContext.redirect(url);

I recommend looking at the JSF specification for more details.

Error messages can be placed on the request scope/session scope/url parameters, as you like.


Assuming a Servlet container, you can use the usual web.xml error page configuration.

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

In your backing bean, you can wrap and throw your checked exceptions in RuntimeExceptions.

Some JSF implementations/frameworks will catch these errors (Apache MyFaces/Facelets), so you'll have to configure them not to.