Author: Abhinav Patel
Welcome all, to the DataWeave series for Mule 4.
If you have not gone through the previous articles, I would recommend you to go through it first to get a basic understanding of Dataweave. In this article, we will try to understand the working of try scope in dw 2.0
We will evaluate a lambda expression within the try scope.
try( () -> someFunction())
The output of a try scope is an object with structure dependent on the outcome of the tested function.
- In case of any error in the function, we will get success and error as the attributes. The success attribute would be set to false in this situation.
- In case of no error, attributes will still be success and result. The success attribute would be set to true in this case.
Let’s start with the most common use case of the Zero Division Error. This example will help us to get familiarity with the syntax.
In the next step, we would try to make some modification in the function.
To analyse this let’s make use of try. To make use of it we need to import the try function from the Runtime module in data weave.
The output that we will get will be:
Note: The same output can be achieved by making a small change in code as mentioned below.
Now let us try to handle this error and send back a custom error message instead of an error object.
The output will be “The divisor value that you have entered is 0”.
Now let’s take this to the next level, where we will be sending non-integral value to function.
The output value will be “Input argument cannot be string”.
Note: If you pass the numeric value as a string then according to current code, dw will sometimes automatically coerce it to numeric and won’t throw any error. So, lets first try to send some character and manually throw an exception using “fail”.
You will get an error object as:
And then try to handle the error:
The output is “User defined error handler invoked”.
Let’s take one last case for the moment, what if you don’t pass the required parameters and see how to handle this.
The output is “Please pass the required parameter-> divisor and dividend”.
Now a small practice statement:
Consider that the yearly income of your company in Cr. is stored in an array. Eg. [123,128,127,190, 83]. Raise an error in the case where the income gets below the minimum threshold value Eg: 100. The response message given back to the customer should be “Master it appears the market was not favorable in 5th year” where the year value represents the index position of the income, for which the income is lower than the threshold value.
I hope you got to learn something new from this walkthrough. Also, if you have any use case, feel free to share it at firstname.lastname@example.org.