AWS API Gateway错误响应会生成502"Bad Gateway"(错误网关),并返回到“ [英] AWS API Gateway error response generates 502 "Bad Gateway"
问题描述
我有一个具有LAMBDA_PROXY集成请求类型的API网关.在Lambda中调用context.succeed
时,响应头将按预期的代码302
发送回去(如下所示).但是,我要处理500
和404
错误,到目前为止,我唯一能确定的就是,在获取502 Bad Gateway
时我错误地返回了错误.我的context.fail
怎么了?
I have an API Gateway with a LAMBDA_PROXY Integration Request Type. Upon calling context.succeed
in the Lambda, the response header is sent back with code 302
as expected (shown below). However, I want to handle 500
and 404
errors, and the only thing I am sure about so far, is that I am returning the error incorrectly as I am getting 502 Bad Gateway
. What is wrong with my context.fail
?
这是我的handler.js
const handler = (event, context) => {
//event consists of hard coded values right now
getUrl(event.queryStringParameters)
.then((result) => {
const parsed = JSON.parse(result);
let url;
//handle error message returned in response
if (parsed.error) {
let error = {
statusCode: 404,
body: new Error(parsed.error)
}
return context.fail(error);
} else {
url = parsed.source || parsed.picture;
return context.succeed({
statusCode: 302,
headers: {
Location : url
}
});
}
});
};
推荐答案
如果您在Lambda函数(或context.fail)中引发异常,API网关将读取该异常,好像后端出了点问题,并返回502.如果这是您期望的运行时异常,并且想要返回500/404,请使用context.succeed方法以及所需的状态代码和消息:
If you throw an exception within the Lambda function (or context.fail), API Gateway reads it as if something had gone wrong with your backend and returns 502. If this is a runtime exception you expect and want to return a 500/404, use the context.succeed method with the status code you want and message:
if (parsed.error) {
let error = {
statusCode: 404,
headers: { "Content-Type": "text/plain" } // not sure here
body: new Error(parsed.error)
}
return context.succeed(error);
这篇关于AWS API Gateway错误响应会生成502"Bad Gateway"(错误网关),并返回到“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!