我正在使用具有无服务器框架的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));
}
}
但是我要返回的对象包含属性状态:502 和 data.message:“内部服务器错误”
这里发生了什么想法?
答案 0 :(得分: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。
答案 1 :(得分:0)
您在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属性,则需要将它们添加到正文中。