Error handling when using a state machine

2.6k views Asked by At

I use a state machine for my c# GUI application. With this I have several states and a single state called ErrorHappened. The state machine can go from every state into these error state. But using this architecture I first know that a error happened when the state machine goes into state ErrorHappened.

But what can I do when during a transition from one state A to a state B an error happens? The problem is that then the state machine goes from state A into state B into state ErrorHappened. Normally I would do an action when the transition into state B is completed. I would not perform this action if there was an error during transition. Of course I could introduce a bool variable like m_ErrorHappened but in my opinion I have a state machine so I am not forced to use any state variables.

I hope the explanation is clear enough to provide any help.

Sample code:

StateMachine sm; // initial state is state A

void AtoB() // executed during transition from A to B
{
  if(DoSomething())
  {
    print("Error");
    // Event ErrorHappened, state machine goes into state Error
    sm.GotoState(ErrorHappened); 
  }
}

void TransitionEnd(State NewState)
{
    if(NewState==B)
    {
        GreenLight();
    }

    if(NewState==Error)
    {
        RedLight();
    }
}

main()
{
    sm.GotoState(B);
}

Now when an error occurs the green and then the red light goes on. Because the state machine goes from state A to state B to error state. Is there a way that the error is detected and only the red light goes on?

1

There are 1 answers

0
Erik Eidt On BEST ANSWER

You might want to change the state machine design so that transitions cannot raise errors: that a transition is guaranteed to be error free by design.

As compared with a model that allows errors in transition, you will have to add more states and transitions, but then that's where your error detection and error handling will go.

In such a design, you would use a general transition mechanism, and any custom handlers would be associated with states, whereas perhaps what you're showing is custom handlers associated with transitions (and maybe generic handlers for states, I can't say from the supplied code).

For example you may need to add a transition from A to some error state in addition to the transition from A to B, with the choice dependent upon a custom handler for A. Alternatively, you might introduce a state in between A and B that decides if there is an error, and goes to B if not and otherwise to an error state.