Contact Us 1-800-596-4880

try

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

try(() -> T): TryResult<T>

Evaluates the delegate function and returns an object with success: true and result if the delegate function succeeds, or an object with success: false and error if the delegate function throws an exception.

Parameters

Name Description

delegate

The function to evaluate.

Example

This example calls the try function using the randomNumber function as argument.
The function randomNumber generates a random number and calls fail if the number is higher than 0.5. The declaration of this function is in the script’s header.

Source

%dw 2.0
import try, fail from dw::Runtime
output application/json
fun randomNumber() =
if(random() > 0.5)
   fail("This function is failing")
else
   "OK"
---
try(() -> randomNumber())

Output

When randomNumber fails, the output is:

{
  "success": false,
  "error": {
    "kind": "UserException",
    "message": "This function is failing",
    "location": "Unknown location",
    "stack": [
      "fail (anonymous:0:0)",
      "myFunction (anonymous:1:114)",
      "main (anonymous:1:179)"
    ]
  }
}

When randomNumber succeeds, the output is:

{
  "success": true,
  "result": "OK"
}

Based on the output of the try function, you can add conditional logic to execute when the result is success: true or success: false.