如何解決使用 Lambda 代理整合時 API Gateway REST API 的 HTTP 502 錯誤?

2 分的閱讀內容
0

我已將 Amazon API Gateway 代理整合設定為與 AWS Lambda 函數搭配使用。當我呼叫 REST API 時,收到組態錯誤和 HTTP 502 狀態代碼。

簡短描述

如果 Lambda 函數的許可不正確,或對 API 請求的回應未正確格式化,則 API Gateway 會傳回 HTTP 502 狀態代碼。

如 Amazon CloudWatch Logs 中顯示的 HTTP 502 錯誤訊息範例

Wed Aug 03 08:10:00 UTC 2022 : Execution failed due to configuration error:
WE Aug 03 09:10:00 UTC 2022 : Method completed with status: 502

-或-

Wed Aug 03 08:20:33 UTC 2022 : Lambda execution failed with status 200 due to customer function error: [Errno 13] Permission denied: '/var/task/lambda_function.py'. Lambda request id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Wed Aug 03 08:20:33 UTC 2022 : Method completed with status: 502

為使 API Gateway 處理 Lambda 函數的回應,該函數必須根據下列 JSON 格式傳回輸出:

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

如需詳細資訊,請參閱用於代理整合的 Lambda 函數的輸出格式

解決方法

  1. 使用 API Gateway 中的 API 儀表板查看 REST API 的 CloudWatch 指標
    -或-
    在 Amazon CloudWatch 主控台中查看 REST API 的日誌事件
  2. 在日誌中,查看 Lambda 函數對 API 的回應格式。如果回應不是所需的 JSON 格式,請重新格式化。
  3. 確認 Lambda 函數的資源政策允許使用 API Gateway 調用函數。
  4. 如果 Lambda 函數由於套件許可問題而執行失敗,請驗證許可。如需說明,請參閱如何對上傳 Lambda 部署套件時的 "permission denied" 或 "unable to import module" 錯誤訊息進行疑難排解?
  5. 確認 Lambda 函數處理常式名稱和組態有效
  6. 如果 Lambda 執行在執行時期失敗,請檢查 Lambda 函數日誌並更新程式碼。
  7. 在 API Gateway 主控台中測試 REST API 方法

回應已正確格式化的範例 Node.js Lambda 函數

**注意:**Node.js Lambda 函數支援非同步處理常式非同步處理常式。下列範例函數使用非同步處理常式。

exports.handler = async (event) => {

    const responseBody = {
        "key3": "value3",
        "key2": "value2",
        "key1": "value1"
    };

    const response = {
        "statusCode": 200,
        "headers": {
            "my_header": "my_value"
        },
        "body": JSON.stringify(responseBody),
        "isBase64Encoded": false
    };

    return response;
};

在此範例回應中,有四個欄位:

  • statusCode 是由 API Gateway 解譯的整數,該整數傳回給 API 方法的呼叫者。
  • headers 被收集,然後與 API 閘道回應一起傳回。
  • 如果您以 JSON 形式傳回資料,則必須將 body 轉換為字串。
    **注意:**您可以使用 JSON.stringify 在 Node.js 函數中處理此問題。其他執行時期需要不同的解決方案,但概念是相同的。
  • 如果您處理的是二進位資料,isBase64Encoded 為必填欄位。如果您不使用此欄位,最佳實務是將值設定為 FALSE

相關資訊

在 API Gateway 中為 REST API 設定 CloudWatch 日誌記錄

使用 Amazon CloudWatch 指標監控 REST API