Replies: 2 comments 2 replies
-
|
I searched a lot across the issues and found some similar cases ( for example this one - #3645 ). From what I understand, when the machine is instantiated, we can subscribe to errors. But there is no way inside the machine to subscribe to that error and make a transition? One workaround that I see is to subscribe for error and once an error is caught we can send an event to the state machine and thus we can transition to the error state which is a final state? |
Beta Was this translation helpful? Give feedback.
-
|
I was about to open an issue but I found this one. import { createActor, fromPromise, setup } from "xstate"
type Input = { shouldThrow: "input" | "actor" | "onDone" | null }
const myPromiseActor = fromPromise<string, Input>(
({ input }) => {
return new Promise((resolve, reject) => {
if (input.shouldThrow === "actor") {
console.error("Throwing error from within the actor's promise.")
reject(new Error("Error from actor"))
} else {
resolve("Promise resolved")
}
})
}
)
const promiseMachine = setup({
types: {
context: {} as Input,
input: {} as Input
},
actors: { myPromiseActor }
}).createMachine({
id: "promiseMachine",
initial: "loading",
context: ({ input }) => input,
states: {
loading: {
invoke: {
src: "myPromiseActor",
input: ({ context }) => {
if (context.shouldThrow === "input") {
console.error("Throwing error from input function.")
throw new Error("Error from input function")
}
return context
},
onDone: {
target: "success",
actions: ({ context }) => {
if (context.shouldThrow === "onDone") {
console.error("Throwing error from within the onDone hook.")
throw new Error("Error from onDone hook")
}
console.log("onDone hook executed successfully.")
}
},
onError: {
target: "failure",
actions: () => {
console.error("Caught error")
}
}
}
},
success: { type: "final" },
failure: { type: "final" }
}
})
const actor = createActor(promiseMachine, { input: { shouldThrow: "onDone" } }).start()
actor.subscribe((state) => {
console.log("Current state:", state.value)
})
One solution to these issue would be for onError to catch allErrors happening in input and in onDone. This could be enabled with a small flag (catchAll: true) to be backward compatible, and eventually be the default in v6. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In one of my states I am invoking a promise actor and have an input inside invoke. My invoke section includes onDone/onError and my input function could throw an error in some cases.
I've just noticed that the onError transition is executed only for errors thrown from promise actor.
What is a possible solution to this cause? Is there an option like the onError transition but for input errors?
Beta Was this translation helpful? Give feedback.
All reactions