Handling Java Errors in Mule 4
This tutorial explains how to handle Java errors in Mule 4.
Join the DZone community and get the full member experience.
Join For FreeMule 4 handles Java code through Java Module. The following new features have been added in Mule 4 for Java:
Java static methods can now be called using an "Invoke Static" component in Java module.
For calling instance method of Java, we need to create an instance of the Java class using a "new" component and then use the "Invoke" component to call the instance method with all relevant arguments, if any.
Mule 4 introduces a formal error concept, and because each component declares the type of errors it can throw, we can identify what error it is going to throw at design time only.
Take a look at the HTTP request component in the below Mule flow:
Looking at the above screenshot, it is clear that we can identify what all possible errors an "HTTP request" component can throw at design time.
This is similar for Java components also, but there is a gap in Java error handling. If we try to know what all possible Java exceptions we can get while executing a Java instance method, we have very high-level error types available at design time.
Problem Statement: If an instance method of a Java class throws two or more Java exceptions from within the "Invoke" component, then how do we perform different actions based on the type of Java exception thrown?
Solution: Below is a complete example for this.
Use Case: I have created a simple Java class for diving two variables, and I am throwing two different exceptions from a Java instance method. Based on the error thrown from the Java instance method, I am setting up the error payload in the error handler section.
Attached is the Java class, which has one instance method called "getIntegerDivisionValue", which takes two string arguments that are coming as queryParameters in an HTTP request. I am trying to convert them into integers using the "Integer.parseInt(String s)" method and then trying to get the division of two numbers.
So if any of the numbers are not able to be converted to an Integer, then the method throws a "NumberFormatException", and if the divisor is 0(zero), then the method throws an "ArithematicException".
/**
*
*/
package org.example.api;
/**
* @author Abhishek Solanki
*
*/
public class IntegerDivision {
public IntegerDivision() {
System.out.println("Inside the constructor");
}
public int getIntegerDivisionValue(String a, String b) {
System.out.println("inside the getIntegerDivisionValue Method");
try {
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if (0 != y) {
return x / y;
} else {
throw new ArithmeticException("Its divide by Zero condition");
}
} catch (NumberFormatException e) {
throw new NumberFormatException("input arguments are not covertable to integer");
}
}
}
So, in this case, every time an "Invoke" component fails, it raises a "JAVA:INVOCATION" error. Hence, it becomes difficult to identify which error is actually thrown by the Java instance method based on errorType using #[error.errorType] expression or using #[error.cause] expression.
We have two ways of catching the actual Java exception generated from this method:
By matching the exception phrase that has been set in method when throwing the exception.
By matching the exception class that has been set in method when throwing the exception.
We have used both ways in each of the "on-error-continue" blocks. Here is the complete flow picture of the Mule 4 application.
Below is the complete XML for your reference:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
xmlns:java="http://www.mulesoft.org/schema/mule/java" xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/java http://www.mulesoft.org/schema/mule/java/current/mule-java.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
<http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="89eb695b-8e40-4e4e-ad25-753bb2464932" >
<http:listener-connection host="0.0.0.0" port="8083" />
</http:listener-config>
<flow name="java-error-handlerFlow" doc:id="70661452-f21f-4488-92c7-daf31268e398" >
<http:listener doc:name="HTTP Listener" doc:id="9e9196e5-d861-4b98-be50-4c71beac650c" config-ref="HTTP_Listener_config" path="/javaErrors">
<http:error-response >
<http:body ><![CDATA[#[payload]]]></http:body>
</http:error-response>
</http:listener>
<try doc:name="Try" doc:id="19be4242-3744-4de2-8567-5bb9df28590c" >
<java:new doc:name="Instantiate the Java Class" doc:id="9953294f-a665-4706-a20c-7382193fec25" class="org.example.api.IntegerDivision" constructor="IntegerDivision()" target="IntegerDivisionObj"/>
<java:invoke doc:name="Invoke getIntegerDivisionValue Method" doc:id="f7e2685c-6ee4-4ede-96a4-11a9aaf3cc10" instance="#[vars.IntegerDivisionObj]" class="org.example.api.IntegerDivision" method="getIntegerDivisionValue(String,String)">
<java:args ><![CDATA[#[{
"a": attributes.queryParams.a,
"b": attributes.queryParams.b
}]]]></java:args>
</java:invoke>
<error-handler >
<on-error-continue enableNotifications="true" logException="true" doc:name="On Error Continue" doc:id="44790e23-b35b-44b6-ab41-898b8c87bd8b" when='#[error.exception.cause.target.class contains "NumberFormatException"]'>
<logger level="INFO" doc:name="first logger" doc:id="82460787-f92c-42a5-b4c1-533e7ae369f7" message="#['this is first logger']"/>
<ee:transform doc:name="Transform Message" doc:id="8493f5ac-4f2d-4b85-99e9-e4d3dce1af43" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
{
exceptionMessage: "Number format exception"
}]]></ee:set-payload>
</ee:message>
</ee:transform>
</on-error-continue>
<on-error-continue enableNotifications="true" logException="true" doc:name="On Error Continue" doc:id="3ac8bdc4-808f-4426-928e-4803bed04b9a" when='#[error.exception.cause.target.localizedMessage contains "Its divide by Zero condition"]'>
<logger level="INFO" doc:name="second logger" doc:id="767f1725-7e92-4f26-b934-b88e508ea852" message="#['this is second logger']"/>
<ee:transform doc:name="Transform Message" doc:id="e4fa1b19-2491-410a-9e64-1cc0c2a22976" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
{
exceptionMessage: "Its divide by Zero condition"
}]]></ee:set-payload>
</ee:message>
</ee:transform>
</on-error-continue>
</error-handler>
</try>
<ee:transform doc:name="Set Final Response" doc:id="efb91acf-a2b5-425d-941c-7a702e48144c" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
{
returnValueIs: payload
}]]></ee:set-payload>
</ee:message>
</ee:transform>
<logger level="INFO" doc:name="completed" doc:id="d97666f2-37c6-4bc0-b89f-75b6da351619" message="#['process completed']"/>
</flow>
</mule>
Hence, we can identify the specific Java exception class by using the following code snippet:
#[error.exception.cause.target.class contains "NumberFormatException"]
If we want to check based on "exception message" that we have set while throwing the exception, then use:
#[error.exception.cause.target.localizedMessage contains "Its divide by Zero condition"]
Mule has provided a granular way to get the exact Java exception and work accordingly.
Happy learning!
Opinions expressed by DZone contributors are their own.
Comments