appccelerate / statemachine

A .net library that lets you build state machines (hierarchical, async with fluent definition syntax and reporting capabilities).
Apache License 2.0
481 stars 128 forks source link

Exception handling in transition #70

Closed 2steuer closed 3 years ago

2steuer commented 3 years ago

Hi there and thanks for the great library.

I'm experiencing a little problem with exceptions occurring during state transition functions. At the moment - at to the point of my understanding - If an exception is thrown within a transition an event is fired which at least allows us to log the error, but the transition is still executed.

Is there a possible way to reject a transition in case of an exception? I.e. the state does not change?

Thank you very much. Merlin

ursenzler commented 3 years ago

Hi Merlin,

Thanks!

The state machine was designed so that the caller of the state machine does not have to deal with exceptions. Therefore exceptions are all caught and never handed over to the caller. When I designed the state machine, I decided that the state machine always change state on an event when there is a suitable transition, regardless of whether there is an exception in an action or not. There is no simple way around this without changing some internal code. I always fired an error event onto the state machine so that it entered an error state on an exception. You can queue a new event during executing a transition action. I did this because we used to model external devices with this state machine and an exception is always an error in some way. If this is not possible in your situation, then it probably would be best to change the code to not switch state in case of an exception. That would require that you would have to return whether an exception occurred on line https://github.com/appccelerate/statemachine/blob/6ae943467fca0472887aefeeeb9d387cb17354f4/source/Appccelerate.StateMachine/AsyncMachine/Transitions/TransitionLogic.cs#L78 and if so not executing the following line. Feel free to copy the code into your solution and change it.

I hope that helps you.

Happy coding Urs

2steuer commented 3 years ago

Hi Urs, Thanks for the reply. I see your point here. And having looked at the code I understand that it is not a "quick one" to implement this.

For the record, my suggestion here is: In the Exception-Event handlers, introduce a flag in the EventArgs to reject the transition. Handling of this, however, is not trivial, as the Exit-Action is usually already performed when the transition Action is executed. I see where this is going :-)

Having a transition to an error state does seem like a suitable workaround. I will see if that works for me.

Thank you again. Merlin