AWS API网关错误响应生成502" Bad Gateway"

时间:2017-03-17 02:01:25

标签: amazon-web-services aws-lambda aws-api-gateway

我有一个带有LAMBDA_PROXY集成请求类型的API网关。在Lambda中调用context.succeed时,响应头部按预期发送回代码302(如下所示)。但是,我想处理500和404错误,到目前为止我唯一确定的是,我正在错误地返回错误,因为我收到了502 Bad Gateway。我的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
                }
              });
        }
    });
};

3 个答案:

答案 0 :(得分:7)

如果在Lambda函数(或context.fail)中抛出异常,API Gateway会将其读取为您的后端出现问题并返回502.如果这是您期望的运行时异常并希望返回500 / 404,将context.succeed方法与您想要的状态代码一起使用并发送消息:

if (parsed.error) {
  let error = {
    statusCode: 404,
    headers: { "Content-Type": "text/plain" } // not sure here
    body: new Error(parsed.error)
}
return context.succeed(error);

答案 1 :(得分:0)

我有同样的问题,在我的情况下问题是我的函数没有在context.done()中返回任何内容。所以我没有context.done(null)而是context.done(null, {});

答案 2 :(得分:0)

我从多件事中得到了502。到目前为止,我已经找到了。

答案1:

claudia generate-serverless-express-proxy --express-module {src/server?} 如果您不使用claudia进行表达,那么此答案将无济于事。

答案2:

Lambda函数->基本设置->超时。将其增加到合理的水平。默认为3秒。但是,第一次构建通常会花费更长的时间。