You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS API Gateway集成非异步Lambda报502错误,求助排查原因

问题描述

我在API Gateway中配置了两个GET请求,都集成了Lambda的Hello World示例,代码几乎一致,唯一区别是一个为异步(Async)、另一个为非异步。异步Lambda运行正常,但非异步调用时API Gateway返回502错误:

{
  "message": "Internal server error"
}

x-amzn-errortype    InternalServerErrorException

启用API Gateway追踪与日志后,日志显示响应格式错误:

Received response. Status: 200, 
Integration latency: 25 ms 
Method completed with status: 502 
Execution failed due to configuration error: Malformed Lambda proxy response 
Endpoint response body before transformations: null

两个Lambda代码如下,响应内容完全一致,角色与权限相同,且Lambda执行无报错,错误仅出现在API Gateway端:

正常运行的异步Lambda代码

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  console.log('Received event:', JSON.stringify(event, null, 2));
  await new Promise((resolve) => setTimeout(resolve, 0));

  const response: APIGatewayProxyResult = {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Hello, World!',
      input: event,
    }),
  };

  return response;
};

运行异常的同步Lambda代码

import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';

export function handler(event: APIGatewayProxyEvent, context: Context): APIGatewayProxyResult {
  console.log('event', event);
  console.log('context', context);

  const response: APIGatewayProxyResult = {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Hello, World!',
      input: event,
    }),
  };

  return response;
}

问题原因与解决方案

核心原因

API Gateway的Lambda代理集成要求同步Lambda函数必须通过context.succeed()、context.fail()或context.done()方法返回响应,而非直接返回值。你的同步Lambda代码直接返回了APIGatewayProxyResult对象,但API Gateway无法识别这种返回方式,导致解析响应时判定格式错误,最终返回502。

而异步Lambda函数返回的是Promise,API Gateway能正确处理Promise的resolve结果,因此可以正常工作。

修复方案

修改同步Lambda的代码,使用context.succeed()返回响应:

import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';

export function handler(event: APIGatewayProxyEvent, context: Context): void {
  console.log('event', event);
  console.log('context', context);

  const response: APIGatewayProxyResult = {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Hello, World!',
      input: event,
    }),
  };

  // 使用context.succeed返回响应
  context.succeed(response);
}

或者,也可以将同步函数改为异步函数(即使没有实际异步操作),这样API Gateway也能正确处理返回值,和正常运行的示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:10:08