【问题标题】:spring state machine throws NullPointerException when you throw exception from your action当您从您的操作中抛出异常时,弹簧状态机抛出 NullPointerException
【发布时间】:2016-06-07 09:43:15
【问题描述】:

当我从 StateMachineConfigurerAdapter 中定义的自定义操作中引发异常时,对状态机的任何后续调用都会引发 NPE,因为它获取 null currentState。

我对状态机的调用是:

PersistStateMachineHandler handler;    
handler.handleEventWithState(
                        MessageBuilder
                                .withPayload(event)
                                .setHeader("key", data)
                                .build()
                        ,
                        previousState
                )

堆栈跟踪是:

java.lang.NullPointerException
    at org.springframework.statemachine.support.AbstractStateMachine.acceptEvent(AbstractStateMachine.java:591)
    at org.springframework.statemachine.support.AbstractStateMachine.sendEvent(AbstractStateMachine.java:202)
    at org.springframework.statemachine.recipes.persist.PersistStateMachineHandler.handleEventWithState(PersistStateMachineHandler.java:81)

原因是 this.currentState.getIds() 正在抛出 NPE,因为 currentState 即将为空。

AbstractStateMachine 中似乎有一些代码问题

protected synchronized boolean acceptEvent(Message<E> message)

最后一行没有处理 currentState != null 条件,因为所有前一行都在处理它。您可以通过显式传递 currentState 来跳过此异常,这通常不是必需的。但是即使给出currentState后,也不是调用persistStateChangeListener的onPersist()方法

【问题讨论】:

    标签: java spring state-machine spring-statemachine


    【解决方案1】:

    一种解决方案是在org.springframework.statemachine.action.Action&lt;S, E&gt; 接口中使用void execute(StateContext&lt;S, E&gt; context); 提供的上下文。

    获得上下文后,您可以通过 StateMachine&lt;S, E&gt; getStateMachine(); 访问 StateMachine

    StateMachine中设置异常void setStateMachineError(Exception exception);

    例如

    context.getStateMachine().setStateMachineError(new IllegalArgumentException("Ooops");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2013-05-24
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多