StepFunctionsのエラーの検証

もちろんです。Failステートメントを使って意図的にエラーを発生させる方法を示す例をお見せします。これにより、Step Functionsのリトライメカニズムをテストすることができます。

下記の例は、Step Functionsの状態マシンでリトライ処理を含めた構成です。このシナリオでは、最初のステートがエラーを発生させ、リトライが行われる様子を観察できます。

{
  "Comment": "A simple AWS Step Functions state machine demonstrating the use of Fail state for retry testing",
  "StartAt": "Invoke ListCommandInvocations",
  "States": {
    "Invoke ListCommandInvocations": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ssm:listCommandInvocations",
      "Next": "CheckForErrors"
    },
    "CheckForErrors": {
      "Type": "Pass",
      "Result": {
        "status": "error"
      },
      "Next": "MaybeFail"
    },
    "MaybeFail": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.status",
          "StringEquals": "error",
          "Next": "FailState"
        }
      ],
      "Default": "SuccessState"
    },
    "FailState": {
      "Type": "Fail",
      "Error": "ListCommandInvocations.CustomTestException",
      "Cause": "This is a custom test exception to trigger retry logic."
    },
    "SuccessState": {
      "Type": "Succeed"
    }
  },
  "Retry": [
    {
      "ErrorEquals": ["ListCommandInvocations.CustomTestException"],
      "IntervalSeconds": 2,
      "MaxAttempts": 3,
      "BackoffRate": 2
    }
  ],
  "Catch": [
    {
      "ErrorEquals": ["ListCommandInvocations.CustomTestException"],
      "Next": "FailureHandled"
    }
  ],
  "FailureHandled": {
    "Type": "Pass",
    "Result": "Error has been handled.",
    "End": true
  }
}

この状態マシンは以下のような流れを持ちます:

  1. Invoke ListCommandInvocationsステート:
  • listCommandInvocations APIコールをシミュレートするタスクです。実際に何らかの処理を行う場合、そのリソースのARNに変更してください。
  1. CheckForErrorsステート:
  • Passステートとして、処理の結果をシミュレートします。ここでは"status": "error"を返すことでエラーを発生させます。
  1. MaybeFailステート:
  • Choiceステートを使って、status"error"であるかをチェックします。エラーであればFailStateに進みます。
  1. FailStateステート:
  • Intentional fail state. ListCommandInvocations.CustomTestExceptionエラーを投げます。
  1. SuccessStateステート:
  • 何も問題がなければ、このステートで正常終了します。
  1. リトライポリシー:
  • ListCommandInvocations.CustomTestExceptionエラーに対するリトライを設定しました。2秒間の間隔で最大3回リトライします。BackoffRateを2 (Exponential backoff) としています。
  1. Catchブロック:
  • ListCommandInvocations.CustomTestExceptionエラーが発生した場合、FailureHandledステートに進み、処理を終了します。

この構成により、Failステートでカスタムエラーを発生させ、リトライ処理が行われる様子を観察できます。エラー処理やリトライロジックのテストに役立ちます。

コメント

タイトルとURLをコピーしました