LP13
LP13

Reputation: 34079

How to handle AggregateException from Lambda function in Statemachine

I have async lambda function. Any exception occurs inside the lambda function gets wrapped as AggregateException. So if state machine is invoking this lambda, it receives it as 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");
        }
    }
}

below is my state machine

{  
  "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
    }
  }
}

since state machine is receiving AggregateException not MyCustomException, it never executes HandleMyCustomException step

How do we handle this. I am using .NET Core 2.0 to develop lambda function

Upvotes: 1

Views: 596

Answers (2)

LP13
LP13

Reputation: 34079

found

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

I have updated my lambda project to to .NET Core 2.1 and then added environment variable UNWRAP_AGGREGATE_EXCEPTIONS with value 1

Upvotes: 1

Milan Cermak
Milan Cermak

Reputation: 8064

You have to catch the right exception - the one your code is throwing. You write that all exceptions are wrapped as AggregateException, so just catch that in the state machine. Replace "ErrorEquals": [ "MyCustomException" ] with "ErrorEquals": [ "AggregateException" ].

Upvotes: 0

Related Questions