Using MEL in Mulesoft to convert a NULL value to a default value

Viewed 2500

I'm using some MEL to set a variable based on the return of an SQL query -

#[payload[0].PRTY_TYPE]

The problem i'm having is that sometimes the PRTY_TYPE can come back as blank.

Rather than using exception handling, can I simply edit the MEL in the variable setting so if it's NULL, it gives it a default value? Like -

IF #[payload[0].PRTY_TYPE] IS NULL THEN 'support@email.com'

2 Answers

Mule 3

Try using a ternary expression for this:

#[payload[0].PRTY_TYPE != null ? payload[0].PRTY_TYPE : 'support@email.com']

You could also do this inline with DataWeave:

#[dw("payload[0].PRTY_TYPE default 'support@email.com'")]


Mule 4

DW is the expression language in Mule 4, so you don't need to call dw:

#[payload[0].PRTY_TYPE default 'support@email.com']

I have done this using the or operator. You can use or operator like :

#[payload[0].PRTY_TYPE or 'support@email.com']

this expression will evaluate to support@email.com if payload[0].PRTY_TYPE is null

According to Mule docs, you can actually go more specific on the check by checking if the property exists using the .? operator, like:

#[payload[0].?PRTY_TYPE or 'support@email.com']

Which I would assume to be safer.

Reference

For more info please check this link for more on chained elements.

Related