Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JSF Exception Handling Example

843844Apr 6 2008 — edited Sep 21 2009
Here is an example of catching a backend exception and displaying it on the UI. It seems like most of the examples in books and such concern themselves with Validators and Converters. If you are trying to catch a backend exception, and you just want to display a UI message for it, see if this will work for you:

JSF tags:
...
<h:commandLink id="myActionLink" value="#{msgs.myLinkText}" binding="#{MyFormBean.uiComponentLink}" action="#{MyFormBean.linkProcessingMethod}"></h:commandLink>
...
<h:messages layout="table" errorClass="Errors" styleClass="AlignLeft"/>
...
And now the exception handling and message creation inside of the managed bean:
private HtmlCommandLink uiComponentLink;

...

/**
 * Method that processes the link action
 * 
 * @return String (action ID)
 */
public String linkProcessingMethod()
{
	try 
	{
		// BEGIN: TEST ONLY
			
		if(1 == 1)	// Always true
			throw new Exception("TEST ERROR MESSAGE DISPLAY");
			
		// END: TEST ONLY
			
	return "dummyPageReference";	// No reference for this in faces-config.xml. Redisplays same page.
       } 
		
	catch (Exception e) 
	{
	    addFacesMessageForUI("Exception detected. Message: " +e.getMessage());
	    return "dummyPageReference";
	}
}
	
/**
 * Add faces message for display on the UI
 * 
 * @param String uiMessage
 */
private void addFacesMessageForUI(String uiMessage)
{
	FacesMessage facesMessage = new FacesMessage(uiMessage);
	FacesContext facesContext = FacesContext.getCurrentInstance();

	// Passing null for the client ID argument to the FacesContext 
	// addMessage() method specifies the message as not belonging
	// to any particular UI component. This will cause the message
	// to be displayed as a general message on the UI
		
	facesContext.addMessage(null,facesMessage);
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 19 2009
Added on Apr 6 2008
3 comments
432 views