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

API Gateway返回500内部错误,Lambda与Authorizer均返回2xx状态码

问题分析与解决建议

问题场景

在API Gateway中配置了带Lambda集成的POST方法,同时启用自定义Authorizer做请求验证。发送请求后,Lambda返回202状态码,Authorizer返回200状态码,但API Gateway最终返回500内部服务器错误。

API Gateway访问日志

{
    "stage": "v1",
    "request_id": "b3d88fff-896a-49f0-a4d6-87bcea71da65",
    "api_id": "25a3fslb53",
    "resource_path": "/testResource",
    "resource_id": "vvvvvvv",
    "http_method": "POST",
    "request_time": "06/Feb/2023:04:17:21 +0000",
    "status_override": "-",
    "status": "500",
    "response_length": "36",
    "response_latency": "2121",
    "lambda": {
        "status": "202",
        "latency": "47",
        "request_id": "56dd16c1-07df-4d35-9dda-0255e0ff9c87",
        "error": "-"
    },
    "authorizer": {
        "status": "200",
        "latency": "2069",
        "request_id": "9026e600-f933-4b1f-8e08-0640c9872a42",
        "error": "-"
    },
    "error": "Internal server error"
}

API Gateway配置(OpenAPI规范)

ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      Name: !Sub "${StageName} Store Comms - Call History Service Gateway"
      EndpointConfiguration:
        Type: REGIONAL
      AccessLogSetting:
        DestinationArn: !GetAtt CallHistoryAPILogs.Arn
        Format: '{"stage":"$context.stage","request_id":"$context.requestId","api_id":"$context.apiId","resource_path":"$context.resourcePath","resource_id":"$context.resourceId","http_method":"$context.httpMethod","request_time":"$context.requestTime","status_override":"$context.responseOverride.status","status":"$context.status","response_length":"$context.responseLength","response_latency":"$context.responseLatency","lambda":{"status":"$context.integrationStatus","latency":"$context.integrationLatency","request_id":"$context.integration.requestId","error":"$context.integrationErrorMessage"},"authorizer":{"status":"$context.authorizer.status","latency":"$context.authorizer.latency","request_id":"$context.authorizer.requestId","error":"$context.authorizer.error"},"error":"$context.error.message"}'

      DefinitionBody:
        openapi: 3.0.3
        info:
          title: 'Call History APIs'
          version: 1.0.0
        paths:
          /testResource:
            post:
              parameters:
              - name: 'xxxxx'
                in: 'query'
                required: true
                schema:
                  type: 'string'
              - name: 'yyyyyy'
                in: 'query'
                required: true
                schema:
                  type: 'string'
              x-amazon-apigateway-integration:
                type: aws
                requestParameters:
                  integration.request.header.X-Amz-Invocation-Type: '''Event'''
                  integration.request.querystring.store_id: "method.request.querystring.xxxxx"
                  integration.request.querystring.yyyyyy: "method.request.querystring.yyyyyy"
                requestTemplates:
                  "application/json": >-
                      { "body":"$util.escapeJavaScript($input.body).replaceAll("\\'","'")",
                      "path":"testResource", "httpMethod":"POST", "queryStringParameters": {
                      "xxxxx": "$input.params('xxxxx')",
                      "yyyyyy": "$input.params('yyyyyy')" } }
                httpMethod: POST
                uri: !Sub 'arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${CallHistoryFunction.Arn}/invocations'
                responses:
                  '202':
                    statusCode: '202'
                    selectionPattern: ""
              responses:
                '202':
                  description: call history successfully saved
              security:
              - Authorizer: []

        components:
          securitySchemes:
            Authorizer:
              type: "apiKey"
              name: "Unused"
              in: "header"
              x-amazon-apigateway-authtype: "custom"
              x-amazon-apigateway-authorizer:
                authorizerUri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:xxxxx:function:xxxxxx4d/invocations"
                authorizerResultTtlInSeconds: 300
                identitySource: "method.request.header.X-Authorization, method.request.header.X-Date"
                type: "request"

      CacheClusterEnabled: true
      CacheClusterSize: "0.5"
      MethodSettings:
        - ResourcePath: "/testResource"
          CachingEnabled: false
          HttpMethod: "POST"
      StageName: v1
      GatewayResponses:
        UNAUTHORIZED:
          StatusCode: 401
          ResponseParameters:
            Headers:
              Access-Control-Allow-Origin: "'*'"
        ACCESS_DENIED:
          StatusCode: 403
          ResponseParameters:
            Headers:
              Access-Control-Allow-Origin: "'*'"
        DEFAULT_5XX:
          StatusCode: 500
          ResponseParameters:
            Headers:
              Access-Control-Allow-Origin: "'*'"
        RESOURCE_NOT_FOUND:
          StatusCode: 404
          ResponseParameters:
            Headers:
              Access-Control-Allow-Origin: "'*'"

排查方向与解决方案

  • 修复请求模板转义错误:请求模板中的replaceAll("\\'","'")转义逻辑错误,应改为replaceAll("\\\\'", "'")。原写法会导致API Gateway解析模板时出错,直接触发500错误。
  • 检查Lambda异步调用响应:因设置了X-Amz-Invocation-Type: 'Event'(异步调用),API Gateway对Lambda的响应格式有严格要求。异步调用下Lambda应返回空响应或符合规范的结构,若返回非空内容可能导致API Gateway解析失败。
  • 验证Authorizer返回格式:自定义请求Authorizer必须返回包含principalId和policyDocument的JSON结构,即使验证通过,格式不符合要求也会引发500。示例正确返回格式:
    {
      "principalId": "user123",
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:xxxx:xxxx/v1/POST/testResource"
          }
        ]
      }
    }
    
  • 启用执行日志获取详情:当前仅配置了访问日志,建议启用API Gateway的执行日志,可获取更具体的错误信息(如模板解析失败、权限配置问题等),精准定位故障点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:31:58