【问题标题】:Handling code/configuration error from entry action classes in spring state machine在spring状态机中处理来自入口动作类的代码/配置错误
【发布时间】:2016-11-03 15:38:36
【问题描述】:

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

【问题讨论】:

  • 任何帮助.. 非常感谢

标签: spring-statemachine


【解决方案1】:

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

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

在状态机配置类中定义转换时,只需指定错误操作和所需操作即可。来自example in the documentation

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 中找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多