Search code examples
muledataweavemule4

Why the "default" keyword acts like "try + catch / orElse" in some cases


I recently noticed an interesting behavior from the default keyword. It acts like try-catch or try-orElse in some situation.

For example, if you try to execute the following script:

%dw 2.0
output application/json
---
("ABC" as Number) default "Invalid number"

you will get the output as Invalid number!!. But if you remove the default part and only try ("ABC" as Number) it will throw an error saying Cannot coerce String (ABC) to Number which is expected.

Looks like the statement is behaving as it was

%dw 2.0
import * from dw::Runtime
output application/json
---
try(() -> ("ABC" as Number)) orElse "Invalid number"

However, this is not the end of it. I cannot find this behavior documented but after some hits and trials I am seeing that it only works for the following errors:

  1. Errors during type Coercion. Try ("ABC" as Number) default "default"
  2. Errors raised by using the function fail. Try (dw::Runtime::fail("ERROR") default "default"

There may be more but I am only able to get the info from hit and trials only as there is no documentation around this behavior that I can find.

I think the #1 is to make developers able to easily do something like

payload.someField as Number default 0

without having them check for a null value before doing the coercion. I mean, otherwise, it would have failed at payload.someField as Number if the field is null, and this will be needed rewritten as

(payload.someField default 0) as Number 

My question is

  1. Is this behavior reliable, and can I use this form payload.someField as Number default 0 without worrying it will fail?
  2. Is there a doc for this behavior of default keyword?

Solution

  • The story about the behavior of default is as you said it has two completely different capabilities.

    1. is the one we all know is that it is when ever the left side is null return what ever is on the right.
    2. It acts as an exception handler for some exceptions (this was inherited from dw 1 and sadly we can not change it)

    What kind of exception are we handling?

    1. Calling a function that doesn't support null
    2. Any Coercion exception (like the one that you found)

    Is this behavior reliable, and can I use this form payload.someField as Number default 0 without worrying it will fail?

    To your answer your question, it is yes but not promoted. I would recommend using try for exception handling. But yes we are not going to change this behavior.

    Is there a doc for this behavior of default keyword?

    I don't see it in Anypoint documentation.