gpt4 book ai didi

java - 当您从操作中抛出异常时,Spring 状态机会抛出 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 09:49:46 27 4
gpt4 key购买 nike

当我从 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 即将为 null。

AbstractStateMachine 中似乎存在一些代码问题

protected synchronized boolean acceptEvent(Message<E> message)

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

最佳答案

一种解决方案是使用 void execute(StateContext<S, E> context); 提供的上下文在 org.springframework.statemachine.action.Action<S, E>界面。

一旦获得上下文,您就可以通过 StateMachine<S, E> getStateMachine(); 访问 StateMachine

StateMachinevoid setStateMachineError(Exception exception); 中设置异常(exception)

例如

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

关于java - 当您从操作中抛出异常时,Spring 状态机会抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com