ShowTable of Contents
Introduction
Exception management is an important issue in almost all applications and system architectures. Exception management consists of the methodologies used for exception handling to set a well-defined communication model between the business layer on one side and the presentation layer (user interface) on the other side. In almost all cases, this model is one-way communication from the presentation to the business layer.
In this article we address the following questions:
-
How does the user interface layer (user interface model, in WebSphere Portlet Factory terms) detect when there are exceptions occurring in the business layer?
-
How is an error message (or even a complete object containing the exception object or other data) transferred from the business model to the user interface model?
-
And, as a consequence, how would this user interface behave (with respect to navigation) when everything is OK vs. when exceptions occurred?
The source of some exceptions can be from a run time exception, such as a database connection failure or division by zero. In this article, we introduce run time exceptions as well as an exception that the code throws, depending on the code logic, and explain how can we pass it from the business layer to the user interface layer.
This article is intended for WebSphere Portlet Factory developers, architects, and designers who want to design systems using WebSphere Portlet Factory. To get the most from this article, you should have completed at least WebSphere Portlet Factory skill level 2 (preferably level 3).
Exception management model
In this section we introduce the technique that we use to manage the exceptions in Portlet Factory technology. The high-level view of our method is shown in figure 1.
Figure 1. Overview of exception management method

Basically, the main flow in any application consists of an input page permitting the user to add some input values and then a business layer containing the business logic, business rules, validation, and so on.
If the inputs are well formatted, the business validation is passed, no run time error occurs, and so the flow should go to the output page. However, if any of these validations happen, the error page should display with the error that occurred to help the user correct the error.
Now let's go into the details more deeply and explain the real components of the technique (see figure 2).
Figure 2. Detailed view of the method

Let’s discuss the two flows (scenarios) represented in this figure.
Success flow
This is the flow that runs when everything is fine; that is, no invalid data inserted, no run time exception occurred, and so on. The flow starts from the Input Page component, which gets the input from the user and then passes it to the UI layer code component, which uses the Service Consumer to call the Service Operation in the business layer.
The business operation runs, calculates the result, and returns it to the UI layer code, which determines that the business completed successfully, so it navigates to the Output Page component.
Exception flow
This flow runs when any one of the path conditions become invalid, such as a run time exception or an input invalidation. As with the success flow, this flow also starts from the Input Page component, then goes to the UI layer code, and then the Service Operation component.
However, when an exception occurs in the Service Operation, it catches the exception and initiates an object of custom exception class by passing to it an error code, depending on the type of exception.
Then this new custom exception object is thrown to the UI layer code, which has a Error Listener component that listens for any exceptions that occur. So this listener catches the exception and runs the Error Handling Code component, which has complete access to this exception coming from the business layer.
The Error Handling Code can get the message from the exception object and navigate to the Error Page to display the message. If a business rule is invalid, then the business logic should create this exception object with a descriptive message code, and the Custom Exception class itself will translate this message code into a “friendly” message from the Resource Bundle component.
The Resource Bundle contains pairs of key values for the messages that are in the application. However, if a run time exception occurs, such as file not found, division by zero, etc, then the business logic is responsible for wrapping this run time exception into a custom exception object.
The Custom Exception here is not mandatory because the business layer can throw the run time exception itself to the user interface layer, but this wrapping step is done to make the casting and handling of the exception (thrown from the business layer) in the user interface layer easier.
In this case the business layer doesn’t throw a lot of exception classes, but throws one exception type containing the message already constructed. In this case the user interface layer should extract only this message and doesn't care whether the original reason of this exception was due to run time or business rules invalidation.
Catching the run time exception in business logic is as simple as catching any exception in JavaScriptTM code via try-catch blocks. But after the custom exception is re-thrown to the user interface layer, the catching of this exception in the UI layer is tricky.
This is tricky because the catching block itself is the Error Listener, and accessing the exception object is done by casting a request attribute called “bowstreet.errorhandler.Exception” to the exception class, and this attribute contains the exception object itself (as discussed in the implementation section below).
Example scenario and requirements
This section introduces a simple scenario and shows the exception management for this scenario. The scenario is constructed of an input page containing two input texts and one button. The requirements state that the application should calculate the division of these two input values (integer division, so for example, 10/3 = 3).
There is another page representing the result, which should be the division of input1 by input2. As an example for business rules, we suppose the rule states that “input1 must be greater than input 2”.
If the inputs are in the correct format (integer; not string nor float), then an output page should appear containing the result of input1/input2. If, however, the data format is wrong (run time exception), or division is by zero (run time exception), or input1 is less than input2 (business-rule generated exception), then an error page should appear that contains an error message.
In the first case (run time exception) the system displays a general error message, while in the second case (business rule validation) a “descriptive” resource-bundled error message is reported.
Exception handling implementation
It’s time for a hands-on demonstration in which we illustrate how to
-
Pass the exception from one model to another (from business model to user interface model)
-
Handle this exception in a user interface model
-
Pass it including some data such as error messages, by means of throwing an exception object, using Portlet Factory technology
The following steps show the necessary builders and related configurations to implement the solution:
1. Create a Resource Bundle file:
A “*.properties” file contains key and value pairs, in which “key” represents an error message ID related to a new exception instance thrown, and “value” is used as the user-friendly error message.
In the attached sample code the resource-bundle file name is “ResourceBundle.properties”, under package “sample.nls”. The contents of the file are the following key, value pairs:
ErrorMessage.General_Error=General Error Occurred
ErrorMessage.input2_greater_than_input1=should input1 be greater than input2 as business rule
2. Create a custom exception class:
public class SampleCustomException extends RuntimeException{}
In this class we embed an error message to make the business model instantiate it, depending on the type of exception that occurred.
Accordingly, the user interface model would catch and handle it by means of reporting an error message to the user:
private String customErrorMessage;
In this class we produce two constructors (one for each exception type) as follows:
public SampleCustomException(WebAppAccess webAppAccess, String resourceBundleName, String ErrorCode, Throwable th)
These will be used when a general exception happens to come from a run time exception. In our sample code, this could happen due to a division-by-zero operation or an invalid input format (see listing 1).
Listing 1. Custom exception-class constructor for run time error
public SampleCustomException(WebAppAccess webAppAccess,
String resourceBundleName,
String ErrorCode,
Throwable th)
{
String strTmp = (String)webAppAccess.callMethod(resourceBundleName+"LookupTableToLabel", ErrorCode);
customErrorMessage = (strTmp == null || strTmp.trim().length() == 0)? ErrorCode : strTmp;
customErrorMessage += "<br><br>Error details: <br>" + th.getMessage();
}
As the code shows, the constructor gets webAppAccess as a parameter, a resource bundle name, error message code to extract the friendly error message from this code from the resource bundle, and finally takes the throwable object itself that is thrown while running.
The code get the error message from the resource bundle and adds to it the throwable object’s message to show the user the details of the run time exception (“Error details: / by zero” for example):
public SampleCustomException(WebAppAccess webAppAccess, String resourceBundleName, String ErrorCode)
This will be used when a business exception occurs as a result of a business rule (in our sample code, the input 1 should be greater than input 2, so the business exception should be thrown if input 2 is greater than input 1).
Both constructors get references to WebAppAccess , resourceBundleName, and ErrorCode. The business model instantiates the exception instantiation, whether it is a run time exception or business exception.
The custom exception class is responsible for this transformation from error code to user-friendly error message, and sets the translated error in the error member attribute of the exception class (see listing 2).
Listing 2. Custom exception-class constructor for business validation error
public SampleCustomException(WebAppAccess webAppAccess,
String resourceBundleName,
String ErrorCode)
{
String strTmp = (String)
webAppAccess.callMethod(resourceBundleName+ "LookupTableToLabel", ErrorCode);
customErrorMessage = (strTmp == null || strTmp.trim().length() == 0)? ErrorCode : strTmp;
}
As shown in the code, the main difference in this constructor is that it doesn’t take the exception object as a parameter because an actual exception is not thrown, instead it's a business validation exception.
So the code just looks for the error code in the resource bundle and adds it as a reported error message; if the code doesn’t map to a friendly error from the resource bundle, the code assigns the error code itself as a friendly error message.
3. Build the business model:
This model should hold the business logic and also throw custom exceptions caused by business rules or exceptions caused by run time exceptions.
Below are the builders in the business model:
-
Localized resource builder. This is a reference to a resource bundle (.properties) file that will be passed as an argument when a new exception is created (see figure 3).
Figure 3. Localized resource builder

-
Service definition builder. This is a service provider that exposes operations to another model (see figure 4).
Figure 4. Service definition builder

-
Service operation builder. This is an operation that is exposed by the provider.
Figure 5. Service operation builder

-
Method builder. Contains business logic such as catching any run time exception that occurs and re-throwing it, but under the custom exception class form (as shown in the steps above, by initiating a custom exception object and passing the real run time exception as a parameter during initiation).
Method builder should be called by the service operation. In the method code, the business logic and business rules should exist and throw a custom exception instance, if a business rule is violated (see listing 3).
This is the same as custom exception being thrown if a general exception (run time exception) occurs, and each kind of exception should use a suitable custom exception constructor.
Listing 3. Method builder source code
int var1,var2;
float result=0;
try
{
var1 = Integer.parseInt(param1);
var2 = Integer.parseInt(param2);
result = var1;
result /= var2;
}
catch (Throwable e)
{
//throw customized exception depending on general error happened as dividing by 0
throw new SampleCustomException(webAppAccess,"BusinessErrorResourceBundle","ErrorMessage.General_Error",e);
}
finally
{
}
if(var2>var1)
{
//throw customized exception depending on business rule
throw new SampleCustomException(webAppAccess,"BusinessErrorResourceBundle","ErrorMessage.input2_greater_than_input1");
}
return result;
}
Note that “BusinessErrorResourceBundle” is the resource bundle name in the business model, and “ErrorMessage.General_Error” and “ErrorMessage.input2_greater_than_input1” are error keys in the resource bundle.
4. Build the user interface model:
This user interface model contains the following main components:
-
CalculatorServiceConsumer service consumer. The builder points to the service provider exposed by the business layer (see figure 6).
Figure 6. CalculatorServiceConsumer service consumer

-
Input Page page. Page that contains the input builders “2 text input” and an action button.
-
CalculateActionList action list. Called from the button on the input page, this action list calls the operation exposed by the business model (see figure 7).
Figure 7. CalculateActionList action list

-
OutPutPage page. The page that has the result of the logic when a normal case (without exception) occurs.
-
ErrorPage page. The page that has the error message coming from the business model.
-
CalculatorErrorHandler error handler. This is the error handler builder that listens to the CalculateActionList action list to run a specific method, in case an exception occurs (see figure 8).
Figure 8. CalculatorErrorHandler error handler

-
ErrorHandlerMethod method. A method that is called when the exception occurs. It extracts the exception object from the request to set the message into a variable and then renders the error page so the error is viewed in this error page.
This throwable object is the exception object that is thrown from the business model, so we can cast it into the Custom Exception class so we are able to access the error message string in it (see listing 4).
Listing 4. ErrorHandlerMethod source code
HttpServletRequest request = webAppAccess.getHttpServletRequest();
Throwable ex = (Throwable) request.getAttribute("bowstreet.errorhandler.Exception");
SampleCustomException custEx = (SampleCustomException) ex;
com.bowstreet.builderutilities.PageAutomationRuntime.assign(webAppAccess, "errorMessage", custEx.getCustomErrorMessage(), false);
webAppAccess.processPage("ErrorPage");
Note that “bowstreet.errorhandler.Exception” is the key to this method, in that by using this attribute in the request scope, the UI model can access the exception that was thrown by the business model (business layer), which in our case is the custom exception object.
After casting the attribute into the custom exception object, you can access the string variable in this object that holds the error message, since it is called by the constructor of the custom exception. The method assign this error string into a local variable in the UI model and then renders the error page which, in turn, renders the error message from this local variable.
-
ErrorMessage variable. Holds the error message coming from the transferred custom exception object.
Navigating the code sample
The code sample attached below is the WebSphere Portlet Factory archive project containing the implementation of the exception management methodology. The code includes two models:
-
UiModel.model. Contains the user interface layer in the implementation, including mainly the input page, out page, error page, service consumer, error handler listener, and error handler implementation.
-
BusinessModel.model. Contains the business layer in the implementation, including the service provider, operation, business logic, and localized resource.
The integration means between the two models is via producer consumer pattern. The code also contains one .properties file:
-
sample / nls / ResourceBundle.properties, which contains the key values pairs
and contains one class:
-
sample / exception / SampleCustomException.java, which contains the implementation of the custom exception class.
Conclusion
This article has demonstrated how to build an exception management-and-handling methodology in WebSphere Portlet Factory. We described how a custom exception class can be used in normal Java applications, and how can we use a resource bundle, treating errors in the code as just error codes and having the translation display in a “.properties” file. By making the translation and error construction one of the custom exception duties and not a business layer duty, we can easily make changes in the error formatting.
We also presented a means of listing and catching an exception in the user interface model, explained how the attribute can hold this object, and how can we cast this variable and treat this exception object as if it exists in the user interface model itself (not transferred from business layer). This serves to combine run time exceptions and business rules exceptions.
Resources
Read the developerWorks® article, “
Building a wizard pattern in IBM WebSphere Portlet Factory V6.1.”
Participate in the WebSphere Portlet Factory discussion forum
Refer to the developerWorks WebSphere Portlet Factory product page.
Learn more about developerWorks WebSphere Portlet Factory Samples: Using Builders.
Read more at the developerWorks WebSphere Portal zone.
About the authors
Amr Rekaby is a Senior Software Engineer who worked for IBM from 2005 through 2009. Currently he is a Technical Project Leader at Hewlett Packard, specializing in business layer technologies such as Hibernate, Enterprise Java Beans, and WebSphere Portlet Factory. He is about to finish his Master's degree in computer science from the Arab Academy for Science and Technology. You can reach him at
rekaby0@hotmail.com or
amr.ali@hp.com.
Amr Darwish is an Advisory Software Engineer, Application Integration & Middleware Solutions Specialist, based at IBM's Cairo, Egypt facility. He has passed through several extensive development and maintenance cycles as part of several IBM internal and external engagements. You can reach Amr at
adarwish@eg.ibm.com or
amrdarwish1975@gmail.com