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

joh*_*mac 5 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
                }
              });
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

Ste*_*ani 11

如果您在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);
Run Code Online (Sandbox Code Playgroud)