【问题标题】:Error Handling in AWS API Gateway and Lambda always return 502AWS API Gateway 和 Lambda 中的错误处理总是返回 502
【发布时间】:2017-07-07 02:24:35
【问题描述】:

我使用无服务器来实现 Lambda 和 Api 网关。 当我实现错误处理时,下面的代码总是得到 502 bad gateway。

handler.js

module.exports.hello = (event, context, callback) => {
  const response = {
      statusCode: 400,
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        "status": "error",
        "message": "Missing Params"
      })
    };
    callback(response);
};

CloudWatch 记录错误。

{
    "errorMessage": "[object Object]"
}

我按照以下 AWS 博客中的“自定义错误对象序列化”方法进行编码。 Ref

【问题讨论】:

    标签: amazon-web-services lambda aws-api-gateway serverless-framework


    【解决方案1】:

    我将回调第一个参数更改为 null 并且工作正常。 Ref

    module.exports.hello = (event, context, callback) => {
      const response = {
          statusCode: 400,
          headers: {
            "Content-Type" : "application/json"
          },
          body: JSON.stringify({
            "status": "error",
            "message": "Missing Params"
          })
        };
        callback(null, response);
    };
    

    【讨论】:

      【解决方案2】:

      这是 Node.js 中的一种常见模式,它被称为 Error-First Callbacks

      基本上,如果您将第一个参数传递给回调,它将被视为错误并被处理。

      正如您所提到的,一旦您输入了callback(null, response);,一切都会按预期工作,因为第一个参数为空。

      【讨论】:

        猜你喜欢
        • 2017-10-04
        • 2019-08-24
        • 2018-11-28
        • 2020-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-15
        • 2017-06-23
        相关资源
        最近更新 更多