提问人:Alexander Chirkov 提问时间:6/18/2023 更新时间:6/21/2023 访问量:164
xstate.js:无法在子服务保护中捕获错误
xstate.js: Not able to catch error in guard of subService
问:
是否有可能在警卫中发现异常?
例如:
const { interpret, createMachine } = require("xstate");
const fetchMachine = createMachine(
{
initial: "start",
states: {
start: {
on: {
LETS_TRY: "subService",
},
},
subService: {
invoke: {
src: () => Promise.resolve(),
onDone: [
{
target: "stop",
cond: "someGuard",
},
],
onError: "stop",
},
},
stop: {
type: "final",
},
},
},
{
guards: {
someGuard: () => {
throw new Error("error in guard");
},
},
}
);
try {
interpret(fetchMachine)
.start()
.send("LETS_TRY");
} catch (e) {
console.log("exception caught", e.message);
}
此代码的预期输出是“捕获异常”,但我收到以下错误消息:
Error: Unable to evaluate guard 'someGuard' in transition for event 'done.invoke.(machine).subService:invocation[0]' in state node '(machine).subService'
示例也可在 codesandbox 上找到。
答:
0赞
z_lander
6/21/2023
#1
否,仅返回或作为确定是否应发生转换的条件。guards
true
false
https://xstate.js.org/docs/guides/guards.html#guards-condition-functions
如果要抛出显式错误,可以尝试使用:action
onDone: [
{
target: "stop",
actions: () => {
throw new Error("error in guard");
},
},
]
或者,如果要读取 promise 抛出的错误,可以从状态中检查对象。event
onError
onError: {
target: "stop",
actions: (context, event) => {
console.log(event.data);
},
}
评论
0赞
Alexander Chirkov
6/22/2023
我不想故意犯错误,但错误可能发生在代码中的任何位置,包括守卫。当它被扔进守卫时,我似乎无法抓住它。
0赞
z_lander
6/22/2023
我现在有你的担忧。从未在生产中尝试过,但我想你可以以这种方式尝试一些东西 codesandbox.io/p/sandbox/......
评论