简体   繁体   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?

I'm writing an API for internal use, and for the first time I'm using the serverless framework .我正在写一个 API 供内部使用,这是我第一次使用无服务器框架 I'm writing a Lambda function in Node.js, and using the AWS API Gateway to connect to it.我在 Node.js 中写了一个 Lambda function,并使用 AWS API 网关连接到它。

In some cases I want to return a custom error message, and I'm trying to write a function that would allow me to do that.在某些情况下,我想返回一条自定义错误消息,我正在尝试编写一个 function 来允许我这样做。 Right now, any time the Lambda process fails, I get a standard message from the API. In the code, if I try to kill the process using process.exit(1) , I get a generic error, even if I've already returned an error using callback() :现在,每当 Lambda 进程失败时,我都会从 API 收到标准消息。在代码中,如果我尝试使用process.exit(1)终止进程,我会收到一般错误,即使我已经使用callback()返回错误:

{
    "message": "Internal server error"
}

If I don't use process.exit(1) , I see the error I returned via callback() in the logs, but the process continues, ultimately timing out:如果我不使用process.exit(1) ,我会在日志中看到我通过callback()返回的错误,但该过程仍在继续,最终超时:

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

I've tried a few different ways of returning an error using the callback() method, but so far I haven't been successful.我尝试了几种不同的方法来使用callback()方法返回错误,但到目前为止我还没有成功。 I've tried this method:我试过这种方法:

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);
}

and this one:还有这个:

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);
}

(Sorry about the minor syntax changes between the two.) (很抱歉两者之间的语法变化很小。)

So far, I haven't been able to return any error to the user via the API. My error always get's logged, and the function continues.到目前为止,我无法通过 API 向用户返回任何错误。我的错误总是被记录下来,function 继续。 Any help would be appreciated.任何帮助,将不胜感激。 Thank you!谢谢!

For reference, the relevant parts of my serverless.yml file:作为参考,我的 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:
      - '*/*'

AWS error callbacks for Node.js do not work as advertised. Node.js 的 AWS 错误回调无法像宣传的那样工作。 According to the docs , all one needs to do is ensure custom errors extend the Error prototype.根据文档,所有需要做的就是确保自定义错误扩展错误原型。 However, after over 10 hours of testing, I've found this is completely untrue.然而,经过 10 多个小时的测试,我发现这是完全不正确的。

The only way to return an error callback that will return anything other than {"message": "Internal server error"} (ie if you have your Lambda function triggered from the API gateway) is to callback the error as though it were a success.返回错误回调的唯一方法是返回除{"message": "Internal server error"}以外的任何内容(即,如果您的 Lambda function 从 API 网关触发)是回调错误,就好像它是成功的一样.

TL;DR: callback(errorResponse, null) does not work, but callback(null, errorResponse) does. TL;DR: callback(errorResponse, null)不起作用,但callback(null, errorResponse)起作用。

Your lambda function needs to return success in order for APIgateway to detect your response.您的 lambda function 需要返回成功,APIgateway 才能检测到您的响应。 Try this:尝试这个:

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.

相关问题 如何使用 API 网关集成访问 Node js AWS Lambda 中的 POST 参数? - How do I access a POST parameter in Node js AWS Lambda with API Gateway integration? 从用 Node.js 编写的 AWS Lambda 函数调用 Python boto3 库 - Call Python boto3 library from AWS Lambda function written in Node.js AWS Lambda function on Java with Serverless framework and GraalVM - AWS Lambda function on Java with Serverless framework and GraalVM 如何通过AWS api-gateway返回一个Base64编码的zip文件供下载 - How do I return a Base64 encoded zip file through AWS api-gateway for download 在 Node.js 中使用 lambda API 网关在 s3 中上传图像(aws-lambda-multipart-parser) - Image Upload in s3 using lambda API gateway in Node js (aws-lambda-multipart-parser) 如何让 AWS API 网关在 AWS Lambda function 中调用 URL? - How to get AWS API Gateway invoke URL in an AWS Lambda function? Terraform 无服务器应用程序与 AWS Lambda 和 API 网关未知令牌? - Terraform Serverless Applications with AWS Lambda and API Gateway unknown token? AWS API Gateway 和 Lambda 返回图像 - AWS API Gateway and Lambda to return image 尝试使用 node.js Lambda 函数在 AWS REST API 配置上使用 Axios 发布数据时出现 CORS 错误 - CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function Aws Lambda - 一起使用 java11 和 node.js - Aws Lambda - Using java11 and node.js together
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM