首页 > 解决方案 > 在 AWS Lambda 错误上返回自定义 http 状态代码

问题描述

我正在使用具有无服务器框架的 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));
}
}

但是我要返回的对象包含属性状态:502data.message:“内部服务器错误”

关于这里发生了什么的任何想法?

标签: aws-lambdaaxiosserverless

解决方案


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

回调仅适用于非异步函数。请参阅完整文档


推荐阅读