【问题标题】:Returning custom http status codes on AWS Lambda error在 AWS Lambda 错误上返回自定义 http 状态代码
【发布时间】:2021-02-24 14:51:52
【问题描述】:

我正在使用具有无服务器框架的 AWS Lambda,并且我想在发生错误时返回自定义 http 状态代码,但是当我使用 axios 调用我的端点时,我总是收到 502 状态代码。

module.exports.handler = async (event, context, callback) => {

try {
 // some stuff
} catch (err) {
 // error here
 let myErrorObj = {
      errorType : "InternalServerError",
      httpStatus : 500,
      requestId : context.awsRequestId,
      trace : {
        "function": "abc()",
        "line": 123,
        "file": "abc.js"
      },
      body: err
    }

    callback(JSON.stringify(myErrorObj));
}
}

但我要返回的对象包含属性 status: 502data.message: "Internal server error"

对这里发生的事情有任何想法吗?

【问题讨论】:

    标签: aws-lambda axios serverless


    【解决方案1】:

    status code 502 表示 lambda 对 API Gateway 的响应格式不正确。

    异步函数的正确响应(如果没有在无服务器 YAML 文件中说明的集成方法,它将使用 Lambda Proxy Integration):

    export const dummyFunction = async (event, context, callback) => 
    {
     // ... logic
       return {
       statusCode: 500,
       body: JSON.stringify({...data}),
       }
    };
    
    

    回调仅适用于非异步函数。全文请参考documentation

    【讨论】:

      【解决方案2】:

      您是否在 Lambda 中使用 API Gateway?如果是这样,则您在回调中返回的内容不正确。您返回的对象必须符合以下格式:https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

      所以您可以只使用callback(err) 并让 AWS 生成 500,或者如果您想要添加错误上下文,例如:

      let myErrorObj = {
          statusCode : 500,
          body: JSON.stringify({
              requestId : context.awsRequestId,
              trace : {
                  "function": "abc()",
                  "line": 123,
                  "file": "abc.js"
              }
              error: err
            }
          })
      }
      callback(null, myErrorObj);
      

      如果您需要 requestId 和 trace 属性,您需要将它们添加到正文中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 2014-06-17
        • 1970-01-01
        • 2012-11-14
        相关资源
        最近更新 更多