You need to enable JavaScript to run this app. AWS API Gateway报502错误 如何在Lambda中集成callback回调处理逻辑
优惠活动
大模型
产品
解决方案
定价
更多

AWS API Gateway报502错误 如何在Lambda中集成callback回调处理逻辑

问题根源排查

你遇到的502错误大概率是代码语法错误触发的,首先存在一个明显的低级错误:

  • 初始化DynamoDB DocumentClient的写法错误,正确写法是new AWS.DynamoDB.DocumentClient(),你把DocumentClient首字母写成了小写,运行时会报类不存在的错误,API Gateway收到Lambda运行异常就会返回502状态码。

两种解决方案

方案1:保留async/await写法(更推荐,无需改造为callback)

你当前用的async异步处理方式是Lambda支持的标准写法,只要修复上述语法错误,返回的响应结构已经符合API Gateway的要求,不需要额外引入callback,修复后的代码如下:

'use strict';
const AWS = require('aws-sdk');

exports.handler = async (event, context) => {
    // 修复DocumentClient首字母大写问题
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    const {
        id,
        productname
    } = JSON.parse(event.body);

    const params = {
        TableName: "Products",
        Item: {
            id: id,
            productname: productname
        }
    };

    try {
        const data = await documentClient.put(params).promise();
        responseBody = JSON.stringify(data);
        statusCode = 201;
    } catch (err) {
        responseBody = `Unable to put product: ${err}`;
        statusCode = 403;
    }

    const response = {
        statusCode: statusCode,
        headers: {
            "Content-Type": "application/json",
            // 有跨域需求可以加这个头避免前端报错
            "Access-Control-Allow-Origin": "*"
        },
        body: responseBody
    };
    return response
};

方案2:改造为callback写法(匹配你找到的示例)

如果要使用callback方式处理异步逻辑,需要去掉handler的async标识,在参数中新增callback,逻辑执行完成后调用callback即可,代码如下:

'use strict';
const AWS = require('aws-sdk');

// 去掉async,新增callback参数
exports.handler = (event, context, callback) => {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    const {
        id,
        productname
    } = JSON.parse(event.body);

    const params = {
        TableName: "Products",
        Item: {
            id: id,
            productname: productname
        }
    };

    documentClient.put(params).promise()
    .then(data => {
        // 成功时调用callback返回响应
        callback(null, {
            statusCode: 201,
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        });
    })
    .catch(err => {
        // 异常时也通过callback返回结构化响应,避免API Gateway报502
        callback(null, {
            statusCode: 403,
            body: JSON.stringify(`Unable to put product: ${err}`),
            headers: {'Content-Type': 'application/json'}
        });
    });
};

额外注意事项

  • 修复后如果仍报502,可以到Lambda函数的监控页查看CloudWatch运行日志,里面会打印具体的错误原因
  • 确保Lambda的执行角色拥有目标DynamoDB表的PutItem权限,权限不足也会触发运行异常返回502

内容的提问来源于stack exchange,提问作者user16353872

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 02:36:03