如何使用Spring State Machine在状态转换过程中引发异常 [英] How to get exception thrown during state transition using spring state machine

查看:1696
本文介绍了如何使用Spring State Machine在状态转换过程中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解,状态转换期间动作可能引发异常.我已经配置了这个简单的状态机:

I am trying to understand, how an exception thrown by an action during a state transition is possible. I‘ve this simple state machine configured:

transitions
    .withExternal()
    .source(State.A1)
    .target(State.A2)
    .event(Event.E1)
    .action(executeAnActionThrowingAnException())

在服务类中,我注入了状态机并发送此事件E1:

In my service class, I injected my state machine and send this event 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状态机获取了抛出的异常,因此发送事件后我无法获得任何响应.但是状态机没有任何错误,这意味着

In my service I just want to know, if and why my state machine wasn‘t able to reached State.A2. Because a thrown exception is fetched by Spring state machine, I am not able to get any response after sending the event. But the state machine hasn‘t any error, which means that

stateMachine.hasStateMachineError()

将返回false.那么,如何获取服务中的信息,发现出了问题,更重要的是出了什么问题?

will return false. So, how can I get the information in my service, that something went wrong and more importantly what?

我请你帮忙.

最诚挚的问候

推荐答案

对于这意味着,如果在过渡期间引发异常,则可以指定和触发其他操作.可以从传递给操作的StateContext中获得该异常.

This means you can specify and additional action to be triggered, if there's an exception raised during the transition. The exception is available from the StateContext passed to the action.

触发错误操作后,可以使用以下方法检索异常:

When your error action is triggered, you can retrieve the exception with:

context.getException();

在错误操作中,您可以做一些事情来处理异常:

Inside the error action you can do a couple of things to deal with the exception:

  • 记录异常和上下文
  • 转换为某些错误状态
  • 清除上下文并转换为相同状态,并尝试执行一些重试逻辑
  • 在上下文中添加一些其他信息,并将上下文返回给调用方

例如:

context.getVariables().put("hasError", true); 
context.getVariables().put("error", ex);

在您的服务(调用方)中,您可以根据需要处理异常,例如:

And in your service(caller) you handle the exception as you like, for example:

public void executeMyLogic() {
    stateMachine.start()
    stateMachine.sendEvent(Event.E1);
    if (stateMachine.getExtendedState().getVariables().containsKey("hasError") {
      throw (RuntimeException)stateMachine.getExtendedState().getVariables().get("error")
    }
}

这篇关于如何使用Spring State Machine在状态转换过程中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆