0

我正在使用状态机构建器在我的应用程序中构建状态机。该应用程序还具有实现 org.springframework.statemachine.action.Action 的 Action 类。这些动作类用于执行每个阶段的入口动作。如果从这些 Action 类中抛出任何异常,即从 execute(StateContext paramStateContext) 方法,我想在使用错误详细信息更新数据库后捕获该异常并发送一个事件(Terminated) 并将状态机驱动到 End 状态。我尝试通过覆盖 stateMachineError(StateMachine stateMachine, Exception e) 方法来使用状态机侦听器。但不幸的是,这不起作用。任何其他用于捕获异常的弹簧状态机组件,在我使用 try catch 将整个代码包装在 Action 类中之前,并在 catch 块内发送 Terminated 事件,以便状态机导航 End 状态。这是我正在使用的构建器。

Builder<String, String> builder = StateMachineBuilder
                .<String, String> builder();
        builder.configureConfiguration()
        .withConfiguration()
        .autoStartup(false)
        .listener(listener())
                .beanFactory(
                this.applicationContext.getAutowireCapableBeanFactory());

private StateMachineListener<String, String> listener() {
        return new StateMachineListenerAdapter<String, String>() {
            @Override
            public void stateChanged(
                    org.springframework.statemachine.state.State<String, String> from,
                    org.springframework.statemachine.state.State<String, String> to) {
                LOGGER.debug("State change to " + to.getId());
            }

            @Override
            public void stateMachineError(
                    StateMachine<String, String> stateMachine, Exception e) {
                e.printStackTrace();
                LOGGER.debug("Ah... I am not getting executed when exception occurs from entry actions");
                LOGGER.debug("Error occured from  " + stateMachine.getState()
                        + "and the error is" + e.toString());
            }
        };
    }

我正在使用 1.1.0.RELEASE 版本的 spring-statemachine-core

4

1 回答 1

0

您是对的,无论是stateMachineError或带有注释的方法@onStateMachineError都不会在错误时执行。这在版本 1.2 中得到解决,目前处于里程碑 1。他们介绍了errorAction哪个是使用状态机上下文执行的:

用户始终可以手动捕获异常,但是通过为转换定义的操作,可以定义在引发异常时调用的错误操作。然后可以从传递给该操作的 StateContext 获得异常。

所需要的只是在状态机配置类中定义转换时指定错误操作以及所需操作。从文档中的示例

public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
        throws Exception {
    transitions
        .withExternal()
            .source(States.S1)
            .target(States.S2)
            .event(Events.E1)
            .action(action(), errorAction());
}

可以在 Spring Statemachine issue #240中找到对此的详细讨论。

于 2016-10-01T15:36:40.003 回答