Skip to content

Commit

Permalink
Allow wildcard transitions to act as "error handlers"
Browse files Browse the repository at this point in the history
  • Loading branch information
Andarist committed Jan 11, 2022
1 parent 80bfe15 commit ddba455
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 30 deletions.
4 changes: 1 addition & 3 deletions packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,9 +718,7 @@ export class Interpreter<

if (
_event.name.indexOf(actionTypes.errorPlatform) === 0 &&
!this.state.nextEvents.some(
(nextEvent) => nextEvent.indexOf(actionTypes.errorPlatform) === 0
)
!this.state.can(_event as any)
) {
throw (_event.data as any).data;
}
Expand Down
83 changes: 56 additions & 27 deletions packages/core/test/invoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1770,8 +1770,6 @@ describe('invoke', () => {
});

it('should call onError only on the state which has invoked failed service', () => {
let errorHandlersCalled = 0;

const errorMachine = Machine({
initial: 'start',
states: {
Expand All @@ -1784,44 +1782,48 @@ describe('invoke', () => {
type: 'parallel',
states: {
first: {
invoke: {
src: () => () => {
throw new Error('test');
},
onError: {
target: 'failed',
cond: () => {
errorHandlersCalled++;
return false;
initial: 'waiting',
states: {
waiting: {
invoke: {
src: () => () => {
throw new Error('test');
},
onError: {
target: 'failed'
}
}
}
},
failed: {}
}
},
second: {
invoke: {
src: () => () => {
// empty
},
onError: {
target: 'failed',
cond: () => {
errorHandlersCalled++;
return false;
initial: 'waiting',
states: {
waiting: {
invoke: {
src: () => () => {
// empty
},
onError: {
target: 'failed'
}
}
}
},
failed: {}
}
},
failed: {
type: 'final'
}
}
}
}
});

interpret(errorMachine).start().send('FETCH');
const service = interpret(errorMachine).start();
service.send('FETCH');

expect(errorHandlersCalled).toEqual(1);
expect(service.state.value).toEqual({
fetch: { first: 'failed', second: 'waiting' }
});
});

it('should be able to be stringified', () => {
Expand Down Expand Up @@ -2641,6 +2643,33 @@ describe('invoke', () => {
})
.start();
});

it('a wildcard transition should be able to receive an error event', (done) => {
const machine = createMachine({
initial: 'fetching',
states: {
fetching: {
invoke: {
src: () => Promise.reject(new Error('test err')),
onDone: {
target: 'complete'
}
},
on: {
'*': {
actions: () => {
done();
}
}
}
},
complete: {
type: 'final'
}
}
});
interpret(machine).start();
});
});

it('invoke `src` should accept invoke source definition', (done) => {
Expand Down

0 comments on commit ddba455

Please sign in to comment.