If you’re not familiar with AWS Step Functions, it is a service where we can create state-machines to orchestrate asynchronous tasks in workflows without worrying too much about any underlying infrastructure and operations. I’ve been using it a lot recently, and I’d like to share the way I implement a finally block in a Step Functions state machine.

In a workflow, there could be some operations that need to be executed no matter what happens, for example, cleaning up temporary resources that are created at the beginning of the workflow. If we relate to Java language, it is similar to what we do with finally block.

try {
  // Do something
} catch (SomeException ex) {
  // Handle exception
} finally { 
  // The things that must happen no matter what
}

In AWS Step Functions, the default behavior when a state reports an exception is to fail the execution entirely, which means the rest of the state in the state machine will not be executed. Step Functions provides the feature to catch exceptions (please refer to Error Handling in Step Functions), but there is no explicit feature for the finally block.

I figured that we could use Catch field with the wildcard exception name States.ALL to implement the finally block. Let’s start with a simple example:

{
  "Comment": "An simple example",
  "StartAt": "DoSomething",
  "States": {
    "DoSomething": {
      "Type": "Task",
      "Resource": "arn:aws:states:${region}:${account}:activity:DoSomethingActivity",
      "Next": "Cleanup"
    },
    "Cleanup": {
      "Type": "Task",
      "Resource": "arn:aws:states:${region}:${account}:activity:CleanupActivity",
      "End": true
    }
  }
}

This is a state machine that has only one step then clean up, and we don’t have any error handling in it yet.

Image for post

State machine diagram

#aws-step-functions #state-machine #error-handling #programming #aws

The “finally” block in AWS Step Functions state machine
13.20 GEEK