Skip to main content
 首页 » 编程设计

Spring 状态机: How to get information that transition is not possible

2025年12月25日41Leo_wl

当我发送在机器当前状态下不可能的事件时,我希望得到类似异常或任何提示的信息。

没有发生异常,而是没有任何反应。我唯一注意到的是:

stateMachine.sendEvent(myMessage) 

返回错误。但以下方法不会返回 true:

stateMachine.hasStateMachineError() 

所以我想没有异常(exception)......!?

有人知道我如何收到“此事件无法应用于状态机的当前状态”之类的错误吗?

提前非常感谢!

请您参考如下方法:

如果有未知事件,状态机不会因错误而失败,而是会忽略它。 获得有关无效事件的更多信息的唯一方法是添加状态机监听器:

public class InvalidEventListener extends StateMachineListenerAdapter { 
 
    @Override 
    public void eventNotAccepted(Message event) { 
        // it is useless to throw an exception here, it is handled at a higher level 
        // here you can add custom logic, but limited. 
        super.eventNotAccepted(event); 
    } 
} 

您必须将此监听器添加到您的状态机:

stateMachine.addStateListener(new InvalidEventListener());