How to use fail function in Mulesoft

This blog demonstrates the use of fail function in MuleSoft

In this blog we will demonstrate the use of the fail function in Mule 4:

Step 1:

Create a Mule Project in Anypoint Studio. Go to File->New->Mule Project

Step 2: 

Name the project appropriately and select the Mule runtime to be used for execution.

Step 3:

The new project gets created and by default the control points to a mule configuration file where one can drag & drop different Mule Components to achieve the business requirement.

Step 4: 

On the right-hand side there is a component palette where we have different modules and different operations under each module.

Step 5:

Drag & drop HTTP Listener on message flow. Double click on http listener component to complete he configuration. The listener component when dropped on message flow inherently becomes part of the mule flow. Mule flow is a core component which helps in orchestrating different mule components.

Step 6: 

Click on + button in connector configuration & change the default port 8081 to a different one if it’s already occupied. Click on Ok.

Step 7:

Populate the path for the api. This gets appended with the host, port while calling the api.

Step 8:

Select the Transform component from the component palette. This component is part of core module.

Step 9:

Drag & drop the component in mule flow. Double click on Transform component.

Step 10: 

Write the dataweave code to leverage fail() which is part of Runtime module.

fail()- This function returns the error with the message which is passed as parameter to the function.

Dataweave Code:

%dw 2.0

import * from dw::Runtime

output application/json

if(payload.message==”” or payload.message == null) fail(“Message is empty”) else “Message is not empty”

Step 11:  

Deploy the Mule application by right clicking on mule project-> Run As -> Mule Application

Step 12:

In the logs we get a success message indicating successful deployment of api.

Step 13:

Go to postman and test the api by populating the endpoint.

http://{localhost} : {port}/{path} -> http://localhost:8089/fail

a) Populate the Post body as shown below :
 

{

“”message” : “Testing the api “

}

b)  Populate the Post body as shown below :
 

{

“message” : “”

}

c)  Populate the Post body as shown below :
 

{

“message” : null

}

Leave a Reply

Your email address will not be published. Required fields are marked *