Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature request] finally in machine #4726

Open
rozbo opened this issue Feb 4, 2024 · 1 comment
Open

[feature request] finally in machine #4726

rozbo opened this issue Feb 4, 2024 · 1 comment

Comments

@rozbo
Copy link

rozbo commented Feb 4, 2024

Description:

Currently, xstate support catch error by subscribe, but if something store in context, or created by callback actor, once error raised, these resource can't be cleanup
image this.

describe('Callback actor with error threw', () => {
  let counter = 1;
  let isOver = false; // a flag to detect clean or not.
  const machine = setup({
    actors: {
      test: fromCallback(({ sendBack }) => {
        const aa = setInterval(() => {
          counter++;
          sendBack({ type: 'haha' + counter });
        }, 100);
        return () => {
          clearInterval(aa);
          isOver = true; // mark we cleand it.
        };
      }),
    },
  }).createMachine({
    invoke: {
      src: 'test',
    },
    initial: 'idle',
    states: {
      idle: {
        on: {
          haha3: {
            actions: () => {
              throw new Error('haha');
            },
          },
        },
      },
    },
  });
  it('should works when throw error', async () => {
    const actor = createActor(machine);
    actor.start();
    // setTimeout(() => {
    //   actor.stop();
    // }, 300);
    try {
      await toPromise(actor);
    } catch (e) {
      actor.stop(); // this not work cause the machine status is error.
      // console.log(actor.getSnapshot());
      expect(e.message).toMatch('haha'); // ✅  we not catch the Error we threw.
    }
    expect(counter).toBeGreaterThan(2); // ✅
    expect(isOver).toBeTruthy(); // 🔴 this will failed , the cleanup function can't reach
  });
});

So, can we provide a way to clean there resource in machine? like Promise's finally , then we can clean some resource whatever whenever whereever errors threw. so that we can coding happly without care about resource cleanup.

ref: https://discord.com/channels/795785288994652170/1203727111312121987

@rozbo rozbo changed the title [feature request] catch all error in machine [feature request] finally in machine Feb 4, 2024
@davidkpiano
Copy link
Member

@Andarist Perhaps the right thing to do is to stop all running actors if an error occurs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants