Contact Free trial Login

try

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.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub