DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations

Trending

  • How to Introduce a New API Quickly Using Micronaut
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Coding
  3. Java
  4. Handling Java Errors in Mule 4

Handling Java Errors in Mule 4

This tutorial explains how to handle Java errors in Mule 4.

By 
Abhishek Solanki user avatar
Abhishek Solanki
·
Updated Jul. 19, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
16.3K Views

Join the DZone community and get the full member experience.

Join For Free

Mule 4 handles Java code through Java Module. The following new features have been added in Mule 4 for Java:

  1. Java static methods can now be called using an "Invoke Static" component in Java module.

  2. 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:Error Declaration

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.

Error Handling in Java component

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: 

  1. By matching the exception phrase that has been set in method when throwing the exception.

  2. 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.

Java-Error-handler Scenario

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!

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!