

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 設定 Lambda 非同步調用的錯誤處理
<a name="invocation-async-configuring"></a>

使用以下設定，設定 Lambda 在非同步調用函數時如何處理錯誤和重試：
+ [MaximumEventAgeInSeconds](https://docs.aws.amazon.com/lambda/latest/api/API_PutFunctionEventInvokeConfig.html#lambda-PutFunctionEventInvokeConfig-request-MaximumEventAgeInSeconds)：Lambda 在捨棄事件之前，將事件保留在非同步事件佇列中的時間上限，以秒為單位。
+ [MaximumRetryAttempts](https://docs.aws.amazon.com/lambda/latest/api/API_PutFunctionEventInvokeConfig.html#lambda-PutFunctionEventInvokeConfig-request-MaximumRetryAttempts)：當函數傳回錯誤時，Lambda 重試的次數上限。

使用 Lambda 主控台或 AWS CLI 設定函數、版本或別名的錯誤處理設定。

------
#### [ Console ]

**設定錯誤處理**

1. 開啟 Lambda 主控台中的 [函數頁面](https://console.aws.amazon.com/lambda/home#/functions)。

1. 選擇一個函數。

1. 選擇**組態**，然後選擇**非同步調用**。

1. 在 **非同步調用** 下方，選擇 **編輯**。

1. 進行下列設定。
   + **Maximum age of event** (事件存留期上限) - Lambda 在非同步事件佇列中保留事件的時間上限，最多 6 小時。
   + **Retry attempts** (重試嘗試) - 當函數傳回錯誤時，Lambda 重試的次數上限 (介於 0 到 2)。

1. 選擇**儲存**。

------
#### [ AWS CLI ]

若要使用 AWS CLI 設定非同步調用，請使用 [put-function-event-invoke-config](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-function-event-invoke-config.html) 命令。下列範例會設定事件存留期為 1 小時且不重試的函數。

```
aws lambda put-function-event-invoke-config \ 
  --function-name error \
  --maximum-event-age-in-seconds 3600 \
  --maximum-retry-attempts 0
```

此 `put-function-event-invoke-config` 命令會覆寫任何在函數、版本或別名上的現有組態。若要設定某個選項而不重設其他選項，請使用 [update-function-event-invoke-config](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-event-invoke-config.html)。下列範例會將 Lambda 設定為在無法處理事件時，將記錄傳送至名為 `destination` 的標準 SQS 佇列。

```
aws lambda update-function-event-invoke-config \
  --function-name my-function \
  --destination-config '{"OnFailure":{"Destination": "arn:aws:sqs:us-east-1:123456789012:destination"}}'
```

------

您應該會看到下列輸出：

```
{
    "LastModified": 1573686021.479,
    "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function:$LATEST",
    "MaximumRetryAttempts": 0,
    "MaximumEventAgeInSeconds": 3600,
    "DestinationConfig": {
        "OnSuccess": {},
        "OnFailure": {}
    }
}
```

當調用事件超過最大存留期，或所有重試嘗試都失敗時，Lambda 會將其捨棄。若要保留已捨棄事件的副本，請設定失敗事件的[目的地](invocation-async-retain-records.md#invocation-async-destinations)。