Bug: throwing an error within `onReceive` in invoked callback service isn't being caught by `onError`
Description
When throwing an error within onReceive in an invoked callback service, it's not caught. Thrown errors outside onReceive are caught properly. Therefore I'm forced to do something like callback({ type: 'ERROR', error }) in order to handle the error properly and transition to an error state in my state machine.
Expected result
I expect the error to be caught, so my callback service fails and I can transition to an error state properly.
Actual result
Error is not caught and state machine ends up in an invalid state.
Reproduction
https://codesandbox.io/s/pensive-curran-6p4vvx?file=/src/index.js
Additional context
Checked with @mattpocock on Stately Discord and seems to be a bug.
This is somewhat related to: https://github.com/statelyai/rfcs/pull/4 . We are planning to have strong guarantees about errors in v5.
This feels like its own thing - surely any error thrown inside an invoked callback should result in the onError transition being taken?
It should but it also doesn't 😅 There are just a lot of errors that are currently swallowed in XState, for instance, onError won't usually be taken in the parent machine when a child machine errors somewhere (like in assign or whatever).
So while we could improve things in v4 bit by bit - I feel like it's better to focus on the algorithm overhaul and ship this improvement in v5. Merging v4 to v5 already has a non-trivial cost and any changes to the core logic like this have the potential of being problematic in this sense.
OK, boss 👍
I believe that https://github.com/statelyai/xstate/pull/4145 & https://github.com/statelyai/xstate/pull/4492 addressed this issue.