簡體   English   中英

如何使用無服務器框架通過 AWS API 網關在 Node.js 中編寫的 AWS Lambda function 上返回錯誤?

[英]How do I return errors on an AWS Lambda function written in Node.js through the AWS API Gateway using the Serverless framework?

我正在寫一個 API 供內部使用,這是我第一次使用無服務器框架 我在 Node.js 中寫了一個 Lambda function,並使用 AWS API 網關連接到它。

在某些情況下,我想返回一條自定義錯誤消息,我正在嘗試編寫一個 function 來允許我這樣做。 現在,每當 Lambda 進程失敗時,我都會從 API 收到標准消息。在代碼中,如果我嘗試使用process.exit(1)終止進程,我會收到一般錯誤,即使我已經使用callback()返回錯誤:

{
    "message": "Internal server error"
}

如果我不使用process.exit(1) ,我會在日志中看到我通過callback()返回的錯誤,但該過程仍在繼續,最終超時:

{
    "message": "Endpoint request timed out"
}

我嘗試了幾種不同的方法來使用callback()方法返回錯誤,但到目前為止我還沒有成功。 我試過這種方法:

async function return_error(callback, context, error, returnCode){
  console.error("FATAL ERROR: ", error);
  let ErrorObj = {
    errorType : "InternalServerError",
    httpStatus : 500,
    requestId : context.awsRequestId,
    errorMessage : error
}
  callback(JSON.stringify(ErrorObj));
  process.exit(1);
}

還有這個:

async function return_error(callback, error, returnCode){
  console.error("FATAL ERROR: ", error);
  callback({
    isBase64Encoded: false,
    statusCode: returnCode,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({"Error Message:": error})
  }, null);
  process.exit(1);
}

(很抱歉兩者之間的語法變化很小。)

到目前為止,我無法通過 API 向用戶返回任何錯誤。我的錯誤總是被記錄下來,function 繼續。 任何幫助,將不勝感激。 謝謝!

作為參考,我的 serverless.yml 文件的相關部分:

service: #Name of service


provider:
  name: aws
  runtime: nodejs8.10
  role: #ARN of Iam role

functions:
  screenshot:
    handler: #Name of handler
    timeout: 30
    memorySize: 1280
    reservedConcurrency: 10
    events:
      - http: 
          method: get
          path: #path
          contentHandling: CONVERT_TO_BINARY
          authorizer:
            type: aws_iam

plugins:
  - serverless-plugin-chrome
  - serverless-apigw-binary
  - serverless-apigwy-binary
package:
  exclude:
    - node_modules/puppeteer/.local-chromium/** 

custom:
  apigwBinary:
    types:
      - '*/*'

Node.js 的 AWS 錯誤回調無法像宣傳的那樣工作。 根據文檔,所有需要做的就是確保自定義錯誤擴展錯誤原型。 然而,經過 10 多個小時的測試,我發現這是完全不正確的。

返回錯誤回調的唯一方法是返回除{"message": "Internal server error"}以外的任何內容(即,如果您的 Lambda function 從 API 網關觸發)是回調錯誤,就好像它是成功的一樣.

TL;DR: callback(errorResponse, null)不起作用,但callback(null, errorResponse)起作用。

您的 lambda function 需要返回成功,APIgateway 才能檢測到您的響應。 嘗試這個:

async function return_error(callback, error, returnCode){
  console.error("FATAL ERROR: ", error);
  callback(null, {
    isBase64Encoded: false,
    statusCode: returnCode,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({"Error Message:": error})
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM