例如,如果我想为无效参数返回一个特定的400错误,或者当lambda函数调用导致创建时返回一个201。
我希望有不同的http状态代码,但是看起来api网关总是返回200状态代码,即使lambda函数返回错误。
发布于 2017-01-31 11:00:35
最简单的方法是使用use LAMBDA_PROXY integration。使用这种方法,您不需要在API Gateway管道中设置任何特殊的转换。
返回的对象必须类似于下面的代码片段:
module.exports.lambdaHandler = (event, context, done) => {
// ...
let response = {
statusCode: 200, // or any other HTTP code
headers: { // optional
"any-http-header" : "my custom header value"
},
body: JSON.stringify(payload) // data returned by the API Gateway endpoint
};
done(null, response); // always return as a success
};
它确实有一些缺点:因为必须特别注意错误处理,并将lambda函数耦合到API Gateway端点;也就是说,如果您不打算在其他任何地方使用它,那么它不是什么大问题。
发布于 2016-11-16 01:16:18
如果使用API Gateway,这是在AWS Compute博客上推荐的方式。检查集成是否与直接Lambda调用一起工作。
var myErrorObj = {
errorType : "InternalServerError",
httpStatus : 500,
requestId : context.awsRequestId,
message : "An unknown error has occurred. Please try again."
}
callback(JSON.stringify(myErrorObj));
对于直接Lambda调用,这似乎是客户端解析的最佳解决方案。
发布于 2016-10-21 20:07:42
我使用的是无服务器0.5。这就是它的工作原理,对于我的情况
s-function.json:
{
"name": "temp-err-test",
"description": "Deployed",
"runtime": "nodejs4.3",
"handler": "path/to/handler.handler",
"timeout": 6,
"memorySize": 1024,
"endpoints": [
{
"path": "test-error-handling",
"method": "GET",
"type": "AWS_PROXY",
"responses": {
"default": {
"statusCode": "200"
}
}
}
]
}
handler.js:
'use strict';
function serveRequest(event, context, cb) {
let response = {
statusCode: '400',
body: JSON.stringify({ event, context }),
headers: {
'Content-Type': 'application/json',
}
};
cb(null, response);
}
module.exports.handler = serveRequest;
https://stackoverflow.com/questions/31329495
复制相似问题