Contact Us 1-800-596-4880

Work With Throwables - Mule 4

The Java module exposes useful DataWeave functions for throwable instances. (In Java, a throwable is a throw statement.)

These functions have been available since DataWeave version 1.2.0.

Check for a Cause

You can check if a throwable was caused by a certain type of exception using the isCausedBy function. This is especially useful when adding logic to error handlers.

package com.me;

public class TaxCalculator {

	public Double calculateTax(Double price) {
		if (price == null) {
			throw new NullPointerException("Must provide a value for price");
		}
		if (price < 0) {
			throw new IllegalArgumentException("Price must be a non-negative value, but was: " + price);
		}
		return price * 0.21;
	}
}

The calculateTax(Double price) method declares the IllegalArgumentException and NullPointerException exceptions.

The next code example lists part of a flow that throws an error during the execution of the invoke operation.

To check which of the Java exceptions occurred during the failed invocation of the calculateTax(Double price) method, use the isCausedBy function in the error handler to add different logic for each of the cases.

<java:new class="com.me.TaxCalculator"
	constructor="TaxCalculator()"
	target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
	class="com.me.TaxCalculator"
	method="calculateTax(Double)">
    <java:args>#[{price: payload.price}]</java:args>
</java:invoke>
<error-handler>
    <on-error-continue
    	when="#[Java::isCausedBy(error.cause, 'java.lang.IllegalArgumentException')]">
        <set-payload value="Negative prices are not allowed."/>
    </on-error-continue>
    <on-error-continue
    	type="#[Java::isCausedBy(error.cause, 'java.lang.NullPointerException')]">
        <set-payload value="There is no price."/>
    </on-error-continue>
</error-handler>

Obtain a Root Cause

The getRootCause function obtains the root cause of a throwable, disregarding any exception wrapping.

In the next example, all tax calculation errors are handled by the FailureHandler class, which has the handle(Throwable) method that takes the root cause of the throwable. To make that possible, the getRootCause function can be used to pass the root cause as an argument to the handle(Throwable) method.

<java:new class="com.me.TaxCalculator"
  constructor="TaxCalculator()"
  target="taxCalculator"/>
<java:invoke instance="#[vars.taxCalculator]"
  class="com.me.TaxCalculator"
  method="calculateTax(Double)">
    <java:args>#[{price: payload.price}]</java:args>
</java:invoke>
<error-handler>
    <on-error-continue>
      <java:invoke-static
      	class="com.me.FailureHandler"
	method="handle(Throwable)">
          <java:args>#[{cause: Java::getRootCause(error.cause)}]</java:args>
      </java:invoke-static>
    </on-error-continue>
</error-handler>
View on GitHub