如何在以下orElstTry函数调用中测试dw::Runtime::try((函数调用的结果?我想匹配结果类型(错误类型(,并根据上一次尝试引发的错误类型采取不同的操作,但如果try((结果状态为true或false,则不必匹配。
我试图模仿典型的try/catch Java风格,在这种风格中我可以捕获各种类型的错误。
你在找这样的东西吗?您基本上需要存储try()
的结果,以便稍后评估
%dw 2.0
output application/json
import * from dw::Runtime
var d = "" /* change to number to work */
---
do {
var opp = try(() -> 1 + d)
---
if(opp.success)
opp.result
else if(opp.error.kind == "UnexpectedFunctionCallTypesException")
"expected error"
else
"unexpected error"
}
我不确定你想要的是什么结果,但正如你所提到的,你可以继续使用orElstTry((进行尝试。下面的示例代码将执行以下操作:如果num是字符串/数字,则尝试添加1,如果失败,则尝试附加"1〃;如果它是一个数组,那么只需写入num的值即可考虑其他情况。
%dw 2.0
output application/json
import * from dw::Runtime
var num = {}
---
{
result: try(() -> num + 1) orElseTry (num ++ 1) orElseTry (num)
}
因此,从上面的代码更改num的值将导致以下结果:
如果num=1
{
"result": {
"success": true,
"result": 2
}
}
如果num=[]
{
"result": {
"success": true,
"result": [
1
]
}
}
如果num={}
{
"result": {
"success": true,
"result": {
}
}
}
我的方法是使用模式匹配器,但使用类型
%dw 2.0
output application/json
type Error<Kind <: String> = {success:false, error: {kind:Kind}}
import * from dw::Runtime
---
try(() -> fail("first try") )
orElseTry fail("second try")
// orElseTry "Three times the charm!" //uncomment to see log message
match {
//if(ue.error.kind == "UserException")
case ue is Error<"UserException"> ->
ue orElse
fail("ERROR: getUsers failed with a UserException error: " ++ write(ue, "application/json"))
else ->
log(
"INFO: One of the try or orElseTry functions succeeded.",
$ orElse fail("Unhandled Error: " ++ write($.error, "application/json"))
)
}
这种类型的模式如何测试try/orElseTry函数捕获的错误类型,然后有条件地失败或记录包含以前捕获的错误信息的消息。如果以前的任何try/或ElseTry函数成功,此模式将记录消息。否则失败函数中的一个抛出包括先前抛出的错误信息的错误;种类";错误。
%dw 2.0
output application/json
import * from dw::Runtime
try( () -> fail("first try") )
orElseTry fail("second try")
//orElseTry "Three times the charm!" //uncomment to see log message
match {
case ue if(ue.error.kind == "UserException") ->
ue orElse fail("ERROR: getUsers failed with a UserException error: " ++ write(ue.error, "application/json"))
case result if(true) -> log(
"INFO: One of the try or orElseTry functions succeeded.",
result orElse fail("Unhandled Error: " ++ write(result.error, "application/json"))
)
}