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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

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

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

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

Related

  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0
  • Generic and Dynamic API: MuleSoft

Trending

  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • Rust, WASM, and Edge: Next-Level Performance
  • Enforcing Architecture With ArchUnit in Java
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Custom Error Handling Framework for an Enterprise Using MuleSoft

Custom Error Handling Framework for an Enterprise Using MuleSoft

Learn how to make that Mule gallop like a horse by creating your own custom exception handling framework for your MuleSoft app.

By 
Rakesh Kumar Jha user avatar
Rakesh Kumar Jha
·
Dec. 22, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
12.9K Views

Join the DZone community and get the full member experience.

Join For Free

As a MuleSoft Certified Architect, Designer and Developer, I recently worked on API implementations for one of our clients using MuleSoft’s CloudHub. One common feature that we needed to use across API implementations was Exception Handling. Mule provides numerous options for handling exceptions in Mule Flows. Mule’s default exception strategy applies to all Mule applications to manage exception in Mule Flows.

Enterprises require more sophisticated error management for their APIs to give a new, distinct meaning to one or more problems that can occur within the API flows. Mule provides a feature to implement custom exception strategy in Mule flows to handle such situations.

However, in an enterprise, we can define one common exception handling framework and use that across all the APIs instead of writing custom exception handling code in each and every API to handle commonly occurring exceptions.

In this article, I will demonstrate how an enterprise can define their common exception handling framework and use it across all the APIs in the organization.

Define Exception Message/Patterns

The very first step towards creating exception handling framework in an enterprise is to identify common exceptions which can happen in Mule Flows and define a custom, meaningful message, message pattern, corresponding HTTP status, etc.

For example, “Invalid header parameter” can be one of the common exceptions which can happen in all the APIs of the organization. To handle this exception, an enterprise can use the below message format.

{
    "transaction": {
        "status": "E",
        "errorCode": "APP-400",
        "errorText": "Header parameter missing or invalid"
    }
}

In this case, the HTTP Status will be - 400. 

The Error Message Format: - JSON.

Similarly, the“Resource not found” exception can be another common exception across all the APIs and can be defined as below, following the same error format we used above to maintain a similar error message structure in an enterprise.

{
    "transaction": {
        "status": "E",
        "errorCode": "APP-404",
        "errorText": "Resource not found"
    }
}

In this case, the HTTP Status will be- 404.

Error Message Format: JSON.

Once all the custom error message formats, HTTP statuses, etc. for commonly occurring exceptions are defined by the enterprise, we can create a reusable component for exception handling which can be used across all the APIs.

Create Exception Handling Reusable Component

Now, since all the exceptions are identified and defined for an enterprise, let’s create a Mule project in Anypoint Studio. In this project, we will only set exception messages, HTTP statuses, etc., which we defined above based on the cause of exceptions using choice component.

As you can see in below ], we have created a Mule project named “exceptionhandling” and in the configuration.xml file, we have a choice activity to set payload and HTTP status based on the exception cause.

  • #[exception.causedBy(org.mule.module.apikit.exception.InvalidHeaderException)] 

  • #[exception.causedBy(org.mule.module.apikit.exception.NotFoundException)]

  • etc.

Below is the code snippet which can demonstrate the choice routing and setting payload and HTTP status as shown in the below screen shot.

<choice doc:name="Choice">
<when expression="#[exception.causedBy(org.mule.module.apikit.exception.InvalidHeaderException)]">
<set-payload value="{
    &quot;transaction&quot;: {
        &quot;status&quot;: &quot;E&quot;,
        &quot;errorCode&quot;: &quot;APP-403&quot;,
        &quot;errorText&quot;: &quot;Header parameter missing or invalid&quot;
    }
}
" doc:name="Set Payload" mimeType="application/json"/>
<set-property propertyName="httpStatus" value="400" doc:name="Property"/>
</when>
<otherwise>
<set-payload value value="{
    &quot;transaction&quot;: {
        &quot;status&quot;: &quot;E&quot;,
        &quot;errorCode&quot;: &quot;APP-500&quot;,
        &quot;errorText&quot;: &quot;Internal Server Errort&quot;
    }
}
 doc:name="Set Payload" mimeType="application/json"/>
<set-property propertyName="httpStatus" value="500" doc:name="Property"/>
</otherwise>
</choice>

Image title

Now once we are done with defining routing and setting payload, we can set HTTP statuses for all identified common exception scenarios. Let’s create a JAR file (exporting this project as a JAR file) of this project which can be used across all the APIs.

Using Exception Handling JAR File in APIs

We will add the exception handling JAR file which we just created to the build path of the API that we want to use. To do this, let’s place a JAR file in src/main/resources folder of the API and right click on Build Path -> Add to Build Path as shown in the screen shot below.

Image title

This will add the exception handling jar file into the API project reference library folder as shown below.

Image title

Now we need this JAR file to be available in the server class path during runtime, which can be achieved using Spring beans, as shown in below code snippet.

<spring:beans>
<spring:import resource="classpath:exceptionhandling-v1.xml" />
</spring:beans>

Now we will call the exception handling JAR file flow from the catch exception handling block of the API as shown below.

<catch-exception-strategy doc:name="Catch Exception Strategy">
            <flow-ref name="exceptionhandlingFlow" doc:name="exceptionhandlingFlow"/>
             <set-property propertyName="http.status"
value="#[message.outboundProperties['httpStatus']]" doc:name="Property" />
</catch-exception-strategy>

The below screenshot shows the implementation of exception handling in an API which is using an exception handling JAR file.

Image title

That concludes the detailed steps which an enterprise can follow to implement their own custom exception handling framework to handle MuleSoft exceptions for all of their APIs. This provides for the reusability of code components, keeps exception message format consistent across all the APIs, and reduces code complexity, effort, and the cost of implementation.

Let’s share our knowledge to expand our MuleSoft community.

 Thank you!

Framework MuleSoft Error message API JAR (file format)

Opinions expressed by DZone contributors are their own.

Related

  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0
  • Generic and Dynamic API: MuleSoft

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!