user1187968
user1187968

Reputation: 8036

AWS Python Lambda: how to raise Exception for step function

I have the following flow for my AWS step function, how should my Python lambda raise MyCustomError?

Just use raise Exception("MyCustomError")? Or I need to do something else? The official doc at https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html use node.js as example, and I don't see any Python examples.

{
   "Comment": "A Hello World example of the Amazon States Language using an AWS Lambda function",
   "StartAt": "HelloWorld",
   "States": {
      "HelloWorld": {
         "Type": "Task",
         "Resource": "arn:aws:lambda:us-east-1:123456789012:function:FailFunction",
         "Retry": [ {
            "ErrorEquals": ["MyCustomError"],
            "IntervalSeconds": 1,
            "MaxAttempts": 2,
            "BackoffRate": 2.0
         } ],
      "End": true
      }
   }
}

Upvotes: 2

Views: 5851

Answers (1)

Grant Lammi
Grant Lammi

Reputation: 1404

I did something super similar to this when I needed to catch and retry an API call we made. On the first connection to Aurora Serverless it can take 30 seconds or so to spin up the cluster. So if we got a timeout I just wanted to throw an exception that Step Functions would then retry.

The Step Function state looks like this, with a different wait for my custom exception versus the standard Lambda ones:

"Hello World": {
  "Type": "Task",
  "Resource": "arn:aws:lambda:us-east-1:123456789012:function:FailFunction"
  "Retry": [
    {
      "ErrorEquals": [
        "Lambda.ServiceException",
        "Lambda.AWSLambdaException",
        "Lambda.SdkClientException"
      ],
      "IntervalSeconds": 2,
      "MaxAttempts": 6,
      "BackoffRate": 2
    },
    {
      "ErrorEquals": [
        "QueryAPIUnavailableException"
      ],
      "IntervalSeconds": 30,
      "MaxAttempts": 5,
      "BackoffRate": 2
    }
  ],
  "End": true      
}

And then the Lambda itself just does a raise on an Exception subclass that is nothing but a pass:

class QueryAPIUnavailableException(Exception): pass

def lambda_handler(event, context):
    message = my_query_api.get_message()
    if (message == 'Endpoint request timed out'):
        logger.info("Query API timed out, throwing exception for Step Function retry")
        raise QueryAPIUnavailableException(message)
    else:
        print(f"Got back message: {message}")

Upvotes: 4

Related Questions