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:
("ABC" as Number) default "default"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
payload.someField as Number default 0 without worrying it will fail?default keyword?The story about the behavior of default is as you said it has two completely different capabilities.
What kind of exception are we handling?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With