简体   繁体   English

AWS Python Lambda:如何引发步骤 function 的异常

[英]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?我的 AWS 步骤 function 有以下流程,我的 Python lambda 应该如何引发 MyCustomError?

Just use raise Exception("MyCustomError") ?只需使用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. 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
      }
   }
}

I did something super similar to this when I needed to catch and retry an API call we made.当我需要捕获并重试我们所做的 API 调用时,我做了一些与此非常相似的事情。 On the first connection to Aurora Serverless it can take 30 seconds or so to spin up the cluster.在第一次连接到 Aurora Serverless 时,启动集群可能需要 30 秒左右的时间。 So if we got a timeout I just wanted to throw an exception that Step Functions would then retry.因此,如果我们遇到超时,我只想抛出一个异常,Step Functions 然后会重试。

The Step Function state looks like this, with a different wait for my custom exception versus the standard Lambda ones:步骤 Function state 看起来像这样,与标准 Lambda 相比,我的自定义异常等待不同:

"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 :然后 Lambda 本身只是对 Exception 子类进行提升,这只不过是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}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM