Skip to content

Not able to catch and rethrow spring state machine error #553

Open
@ArpanMajumdar

Description

@ArpanMajumdar

I am working on a project that deals with a contract workflow. I want the state machine to throw an error if a wrong event is sent. I tried using listener to catch the exception thrown by state machine as given in the documentation but I am not able to rethrow error to show an exception message.

Here is my listener

public class ErrorStateMachineListener
    extends StateMachineListenerAdapter<AgreementSubStatus, AgreementEvents> {

  @Override
  public void stateMachineError(
      StateMachine<AgreementSubStatus, AgreementEvents> stateMachine, Exception exception) {
    log.error("Access is denied. Illegal state transition");
    throw new AccessDeniedException("Access is denied");
  }

@Override
  public void eventNotAccepted(Message<AgreementEvents> event) {
    log.info("Inside eventNotAccepted");
    throw new AccessDeniedException("Access is denied");
  }
}

Here is the state machine configuration where I registered the listener.

    // Configure state machine
    builder
        .configureConfiguration()
        .withConfiguration()
        .autoStartup(true)
        .listener(listener())
        .and()
        .withSecurity()
        .enabled(true);

Here is the stack trace obtained after throwing custom exception from the listener.

com.tgt.tvi.libs.basesecurity.exception.AccessDeniedException: Access is denied
	at com.tgt.tvi.apis.agreement.statemachine.ErrorStateMachineListener.eventNotAccepted(ErrorStateMachineListener.java:59)
	at org.springframework.statemachine.listener.CompositeStateMachineListener.eventNotAccepted(CompositeStateMachineListener.java:82)
	at org.springframework.statemachine.support.StateMachineObjectSupport.notifyEventNotAccepted(StateMachineObjectSupport.java:193)
	at org.springframework.statemachine.support.AbstractStateMachine.notifyEventNotAccepted(AbstractStateMachine.java:224)
	at org.springframework.statemachine.support.AbstractStateMachine.sendEventInternal(AbstractStateMachine.java:606)
	at org.springframework.statemachine.support.AbstractStateMachine.sendEvent(AbstractStateMachine.java:218)
	at org.springframework.statemachine.support.AbstractStateMachine.sendEvent(AbstractStateMachine.java:230)

I've also tried putting a try-catch block around sendEvent method but it doesn't come inside the catch block.

try{
        stateMachine.sendEvent(action);
      }catch (Exception e){
        log.error("State machine exception");
   }

Please tell what approach should I take to catch state machine errors to rethrow them and perform some logic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions