views:

7217

answers:

4

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? Please help.

+3  A: 

Hello,

The general way to display error message to the user in JSF is to use FacesMessage:

On Java side:

...
if (errorOccurred) {
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("An error occurred blabla..."));
}

and in the JSF (JSP or XHTML) page, simply use the <h:messages/> component in your page in order to display the error.

romaintaz
+4  A: 

JSF 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.

McDowell
@McDowell - this was an excellent response, I wish I could give you 10 points for your answer.
Richard Clayton
+1  A: 

You can put

<%@ page errorPage="error.jsp" %>

in jour jsp/jsf page. In error.jsp, jou would have:

<%@ page isErrorPage="true" %>

isErrorPage="true" will give your page another implicit object: exception (the same way you already have request and response on jsp page). You can then extract message from exception.

Additional details

Slartibartfast
A: 

Apologies if resurrecting this thread steps on any toes, but as I recently found the answer here the most useful in my recent web search, I would like to point out that JSF 2 now has a mechanism for handling exceptions:

http://java.sun.com/javaee/6/docs/api/javax/faces/context/ExceptionHandler.html

I don't know much about it yet (I have to use JSF 1.2), but if you have the same issue as the question above and can use JSF 2, it may be worth checking it out as an alternative solution to the (excellent) answers above.

authentictech