如何从Statemachine中的Lambda函数处理AggregateException

时间:2019-01-31 16:54:38

标签: aws-lambda aws-sdk aws-step-functions

我有async lambda函数。 lambda函数内部发生任何异常,并包装为AggregateException。因此,如果状态机正在调用此lambda,则它将作为AggregateException

接收
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace MyFunction
{
    public class MyHandler
    {
        public Payload DoWork(Payload payload, ILambdaContext context)
        {
           throw new MyCustomException("This is test");
        }
    }
}

下面是我的状态机

{  
  "StartAt": "DoWork",
  "States": {        
     "DoWork":{      
      "Type":"Task",
      "Resource":"arn:aws:lambda:us-west-2:xxxxx:function:MyHandler:dev",
      "Next":"OK",
       "Catch": [
         {
            "ErrorEquals": [ "MyCustomException" ],
            "Next": "HandleMyCustomException"
          },
          {
            "ErrorEquals": [ "States.ALL" ],
            "Next": "HandleAllErrors"
          }
      ]
    },       
    "HandleAllErrors": {      
      "Type": "Fail",
      "Cause": "UnknownError",
      "Error": "Unable to perform work."      
    },
    "HandleMyCustomException":{      
      "Type":"Fail",
      "Cause":"MyCustomError",
      "Error":"An unknown error occurred while processing. Please check the logs."
    },
    "OK": {
      "Type": "Pass",
      "Result": "The request has succeeded.",
      "End": true
    }
  }
}

因为状态机接收的是AggregateException而不是MyCustomException,所以它从不执行HandleMyCustomException步骤

我们该如何处理。我正在使用.NET Core 2.0开发lambda函数

2 个答案:

答案 0 :(得分:1)

找到

https://github.com/aws/aws-lambda-dotnet/issues/211#issuecomment-459454290

我已将lambda项目更新为.NET Core 2.1,然后添加了值为UNWRAP_AGGREGATE_EXCEPTIONS的环境变量1

答案 1 :(得分:0)

您必须捕获正确的异常-您的代码正在抛出的异常。您将所有异常都包装为AggregateException,因此只需在状态机中捕获即可。将"ErrorEquals": [ "MyCustomException" ]替换为"ErrorEquals": [ "AggregateException" ]