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:
- Errors during type Coercion. Try
("ABC" as Number) default "default"
- 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
- Is this behavior reliable, and can I use this form
payload.someField as Number default 0
without worrying it will fail? - Is there a doc for this behavior of
default
keyword?