Warning: A non-numeric value encountered in /home/customer/www/archive.ricston.com/public_html/wp-content/themes/Divi/functions.php on line 5766

Back after a brief hiatus, I thought I’d build upon one of my previous articles related to Mule-aware services.

In that article, I explained how a service can become aware of its surroundings and the Mule environment it is in. Naturally, services should not be so tightly coupled to the framework, so this mechanism is discouraged. Allow me to demonstrate how being in touch with your Mule environment can help.

Consider the following method within a service:

public int doDivision (Integer a, Integer b) throws Exception {
	if (b != 0) {
		return a / b;
	} else {
	  // Cannot divide by zero
	  if (myService.getModel().getExceptionListener() != null) {
		// If there is an exception strategy,
		// then let Mule handle the exception
		throw new Exception ("Cannot perform division!");
	  } else {
		//Handle this gracefully
		return 0;

In this method, we’re performing a simple arithmetical function, just dividing two integers with one another. I want to check for a division by zero and handle this gracefully. Using this service in a Mule application, means that I have two options:

1. Use an exception strategy to catch the exception and handle it consistently on the bus.
2. Catch the exception inside the class and handle the exception at source.

The thing is, my service does not know if it is configured to have an exception strategy and it may exist within a model that may or may not have such a strategy. I looked at the methods inside the ServiceAware interface and found a getExceptionListener() method which I thought would do the trick.

Unfortunately, it does not.

getExceptionListener() always returns something even if no exception strategy is configured in the Mule config. Clearly, this method was not enough for my needs so I dug deeper.

getExceptionListener() returns an ExceptionListener which, in Mule terms, is an exception strategy. I found out that if a strategy is configured then it would be initialised and realised that I could use this as my flag. I also realised that rather than check for the strategy in the model, it makes more sense to check for one on the service itself. I therefore changed my conditional statement in the code above to this:

DefaultServiceExceptionStrategy strategy =
	(DefaultServiceExceptionStrategy) myService.
if (strategy.isInitialised()) {

Here, I extract (and type cast) the exception listener associated with the service no matter where it is configured. Working with the DefaultServiceExceptionStrategy, I can now test to see if one was configured (i.e., initialised) or not and work accordingly.