statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
26.98k stars 1.24k forks source link

Bug: Promise actor error handling doesn't work as documented #4852

Closed fusionstrings closed 5 months ago

fusionstrings commented 5 months ago

XState version

XState version 5

Description

Promise actor error handling doesn't work as documented.

It's notable that if actor is invoked with onDone and onError then it works as expected but in that case there must be an output property in machine as documented here.

Here is repository which reproduces the error.

Expected result

Directly using promise actor doesn't need to have these boilerplates, as the output is the return value of the promise.

Actual result

This works in case of success but not in case of thrown error.

Machine never reaches to snapshot.status === 'error' because thrown error terminates the process.

Reproduction

Code Sandbox

Additional context

No response

Andarist commented 5 months ago

The docs are wrong here - errored snapshots are never given to the next listeners. You can handle errors in this situation like this:

const { fromPromise, createActor } = require("xstate");

const promiseLogic = fromPromise(async () => {
  // ...
  throw new Error("Something went wrong");
});

const promiseActor = createActor(promiseLogic);
promiseActor.subscribe({
  error: (error) => {
    console.log(error);
  },
});

promiseActor.start();
davidkpiano commented 5 months ago

Fixed the documentation: https://stately.ai/docs/promise-actors#promise-actor-error-handling

fusionstrings commented 5 months ago

Thanks 🙏