node.js - 如何使用无服务器框架通过 AWS API Gateway 返回以 Node.js 编写的 AWS Lambda 函数上的错误?

标签 node.js aws-lambda aws-api-gateway serverless-framework serverless

我正在编写一个供内部使用的 API,这是我第一次使用 serverless framework 。我正在 Node.js 中编写 Lambda 函数,并使用 AWS API Gateway 连接到它。

在某些情况下,我想返回自定义错误消息,并且我正在尝试编写一个允许我执行此操作的函数。现在,每当 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向用户返回任何错误。我的错误总是被记录下来,并且该功能会继续。任何帮助,将不胜感激。谢谢!

作为引用,我的 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 错误回调并不像宣传的那样工作。根据docs ,所需要做的就是确保自定义错误扩展错误原型(prototype)。然而,经过10多个小时的测试,我发现这是完全不正确的。

返回错误回调的唯一方法是返回 {"message": "Internal server error"} 以外的任何内容(即,如果您从 API 网关触发了 Lambda 函数)回调错误,就好像它成功了一样。

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

关于node.js - 如何使用无服务器框架通过 AWS API Gateway 返回以 Node.js 编写的 AWS Lambda 函数上的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53345168/

相关文章:

aws-lambda - 如何限制特定 API 网关路由的负载大小

amazon-web-services - --rest-api-id和--resource-id是什么,我在哪里找到它们?

amazon-web-services - Docs 中的 AWS API Gateway IAM 策略角色在模拟中失败

javascript - Node - Request.js ECONNRESET 错误仅在服务器上

javascript - 区分 JavaScript 中定义的和通用的 JSON 对象

javascript - DynamoDB 无法按范围键获取项目?

node.js - 使用 async/await 在 AWS lambda 上未处理的 promise 拒绝

node.js - 使用 socket.io-client 发送 cookie

node.js - 编写 AWS Lambda Nodejs api 的最佳实践或指南

amazon-web-services - AWS 发布/订阅消息模式