Is it possible to catch an exception in a guard?
For example:
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);
}
The expected output of this code is "exception caught" but instead I am getting the following error message:
Error: Unable to evaluate guard 'someGuard' in transition for event 'done.invoke.(machine).subService:invocation[0]' in state node '(machine).subService'
Example is available also on codesandbox.