Creating an exception inside DataWeave

  • March 16, 2020

This technical article documents how to raise an error inside DataWeave based on conditions provided. DW 2.0 provides two operators to create errors inside DataWeave code — “fail” and “failif.”

How it worked in Mule 3

Assume a scenario where you need to throw an error for a particular value in the incoming field. There were common two methods:

  • Use a Validation component to validate the field value.
    Limitation : If the validation is checking only the datatype, then particular field value validation is not possible
  • Use a Lookup function to call a flow containing a groovy component that throws an error with desired message.
    thrownewException(‘Exception Message’)

How it works in Mule 4

Mule 4 has a Runtime[dw::Runtime] module that allows the user to interact with DataWeave engine. This module provides two operators to create the error inside DataWeave:

Fail operator

This throws the error message when specified. It’s usually provided based on a condition.

Fail operator

This sample code will throw the error with the given message.

Throw Custom Error

Failif operator

This operator throws an error when the given expression is true or else it forwards the given value.

Failif operator

This code will throw the given error.

Failed Error

Note: Make sure to import the Runtime module before using these two operators.

— By Rithul Kumar