【问题标题】:Correct Error Handling in Spring Statemachine纠正 Spring Statemachine 中的错误处理
【发布时间】:2017-09-28 02:39:30
【问题描述】:

我正在评估 Spring Statemachine 并希望 了解如何从过渡中恢复 错误。

我为执行的操作定义了错误操作 在过渡期间。 S1_TO_S2_ACTION的执行 导致在S1_TO_S2_ERROR_HANDLING 中处理的异常。

我可以处理操作中的错误,但我该如何恢复 错误?我试图在错误处理程序 (context.getStateMachine().sendEvent(Events.RECOVER)) 中发送一个事件,但没有任何效果。

@Configuration
@EnableStateMachine
class StateMachineConfig
    extends EnumStateMachineConfigurerAdapter<States, Events> {

    Action<States, Events> S1_TO_S2_ERROR_HANDLING = context -> {
        System.out.println(BO + " ERROR!!!");

        System.out.println("E: " + context.getException());
        System.out.println("S: " + context.getSource().getId());
        System.out.println("T: " + context.getTarget().getId());
    };


    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
        throws Exception {

        transitions
        .withExternal()
        .source(States.SI).target(States.S1).event(Events.E1)
        .action(TRANS_ACTION)
        .and()

        .withExternal()            
        .source(States.S1).target(States.S2).event(Events.E2)
        .action(S1_TO_S2_ACTION, S1_TO_S2_ERROR_HANDLING)
        .and()

        .withExternal()
        .source(States.S2).target(States.SE).event(Events.E3)
        .action(TRANS_ACTION);
    }
}

之后调用stateMachine.hasStateMachineError() 令人惊讶地返回false

我可以在错误操作中从错误中恢复谁以及为什么hasStateMachineError() 如果在转换过程中抛出异常,则返回 false

【问题讨论】:

  • 我在这个话题上取得了一些进展,之后会发布我的结果。

标签: java spring spring-statemachine


【解决方案1】:

我认为,你需要明确地这样做:

try
    {
        ..
    }
    catch (WhateverException e)
    {
        stateMachine.setStateMachineError(e);
        throw e;
    }

在状态机转换函数内部。

我发布了另一个问题的答案,可能也与您相关:https://stackoverflow.com/a/46519081/1258249

【讨论】:

    【解决方案2】:

    您是否想过在StateContext 的extendedSstate 中的变量映射中放置一个标志,并在处理完事件后检索它?然后,您可以通过获取 stateMachineAccess 并在其上调用 resetStateMachine 来重置状态机。

    比如在你的S1_TO_S2_ERROR_HANDLING,你可以这样做

    context.getExtendedState().getVariables().put("recover", true);
    

    然后,在您向状态机对象发送事件后,可能在您的服务层中,检查其上下文变量是否包含真正的恢复标志,并将其重置为源状态。

    【讨论】:

    • 如何获取这个stateMachineAccess并调用resetStateMachine?
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多