如何使用 spring 状态机在状态转换期间抛出异常
How to get exception thrown during state transition using spring state machine
我试图了解,状态转换期间操作抛出的异常是如何可能的。我已经配置了这个简单的状态机:
transitions
.withExternal()
.source(State.A1)
.target(State.A2)
.event(Event.E1)
.action(executeAnActionThrowingAnException())
在我的服务 class 中,我注入了我的状态机并发送了这个事件 E1:
@Service
public class MyService() {
@Autowired
private StateMachine<State, Event> stateMachine;
public void executeMyLogic() {
stateMachine.start()
stateMachine.sendEvent(Event.E1);
// how to get thrown exception here
}
}
在我的服务中,我只想知道我的状态机是否以及为什么无法到达 State.A2。因为抛出的异常是由 Spring 状态机获取的,所以在发送事件后我无法得到任何响应。但是状态机没有任何错误,这意味着
stateMachine.hasStateMachineError()
将 return 错误。那么,我怎样才能在我的服务中获得信息,知道哪里出了问题,更重要的是什么?
感谢您的帮助。
此致
对于transitions exceptions, there's an overload for the actions method available in the TransitionConfigurer
action(Action<S,E> action, Action<S,E> error)
这意味着如果在转换期间出现异常,您可以指定要触发的其他操作。异常可从传递给操作的 StateContext
获得。
当您的错误操作被触发时,您可以通过以下方式检索异常:
context.getException();
在错误操作中,您可以做几件事来处理异常:
- 记录异常和上下文
- 转换到某个错误状态
- 清除上下文并转换到相同状态并尝试执行一些重试逻辑
- 向上下文添加一些附加信息,return向调用者添加上下文
例如:
context.getVariables().put("hasError", true);
context.getVariables().put("error", ex);
并且在你的服务(调用者)中你可以随意处理异常,例如:
public void executeMyLogic() {
stateMachine.start()
stateMachine.sendEvent(Event.E1);
if (stateMachine.getExtendedState().getVariables().containsKey("hasError") {
throw (RuntimeException)stateMachine.getExtendedState().getVariables().get("error")
}
}
我试图了解,状态转换期间操作抛出的异常是如何可能的。我已经配置了这个简单的状态机:
transitions
.withExternal()
.source(State.A1)
.target(State.A2)
.event(Event.E1)
.action(executeAnActionThrowingAnException())
在我的服务 class 中,我注入了我的状态机并发送了这个事件 E1:
@Service
public class MyService() {
@Autowired
private StateMachine<State, Event> stateMachine;
public void executeMyLogic() {
stateMachine.start()
stateMachine.sendEvent(Event.E1);
// how to get thrown exception here
}
}
在我的服务中,我只想知道我的状态机是否以及为什么无法到达 State.A2。因为抛出的异常是由 Spring 状态机获取的,所以在发送事件后我无法得到任何响应。但是状态机没有任何错误,这意味着
stateMachine.hasStateMachineError()
将 return 错误。那么,我怎样才能在我的服务中获得信息,知道哪里出了问题,更重要的是什么?
感谢您的帮助。
此致
对于transitions exceptions, there's an overload for the actions method available in the TransitionConfigurer
action(Action<S,E> action, Action<S,E> error)
这意味着如果在转换期间出现异常,您可以指定要触发的其他操作。异常可从传递给操作的 StateContext
获得。
当您的错误操作被触发时,您可以通过以下方式检索异常:
context.getException();
在错误操作中,您可以做几件事来处理异常:
- 记录异常和上下文
- 转换到某个错误状态
- 清除上下文并转换到相同状态并尝试执行一些重试逻辑
- 向上下文添加一些附加信息,return向调用者添加上下文
例如:
context.getVariables().put("hasError", true);
context.getVariables().put("error", ex);
并且在你的服务(调用者)中你可以随意处理异常,例如:
public void executeMyLogic() {
stateMachine.start()
stateMachine.sendEvent(Event.E1);
if (stateMachine.getExtendedState().getVariables().containsKey("hasError") {
throw (RuntimeException)stateMachine.getExtendedState().getVariables().get("error")
}
}