【问题标题】:Lambda execution failed with status 200 due to customer function error: 'name'由于客户函数错误,Lambda 执行失败,状态为 200:“名称”
【发布时间】:2022-02-04 23:05:58
【问题描述】:

我是 AWS 服务的新手。尝试使用 AWS SAM(yaml)、Lambdas 和 API Gateway 实现简单的 CRUD。 面临POST方法的问题。 Lambda 本身工作正常,但如果我在 API Gateway 中尝试它 - 获取:

Lambda execution failed with status 200 due to customer function error: 'name'

这是 Lambda 代码本身:

import json
import boto3
import os


dynamodb = boto3.resource('dynamodb')
table_name = os.environ.get('DYNAMO_TABLE', 'dragons-table')
region = os.environ.get('REGION_NAME', 'us-east-1')
table = dynamodb.Table(table_name)


def lambda_handler(event, context):
    table.put_item(
        Item={
            'name': event['name'],
            'breed': event['breed'],
            'danger_rating': event['danger_rating']
        }
    )
    response = {
        'message': "Item added"
    }
    return {
        "statusCode": 201,
        "body": json.dumps(response),
    }

这是执行后的日志:

Thu Feb 03 10:48:15 UTC 2022 : Endpoint response body before transformations: {"errorMessage": "'name'", "errorType": "KeyError", "requestId": "83fcc181-b4b5-4a6d-b035-4ea12eaa892e", "stackTrace": ["  File \"/var/task/post_dragons.py\", line 13, in lambda_handler\n    name = event['name']\n"]}
Thu Feb 03 10:48:15 UTC 2022 : Lambda execution failed with status 200 due to customer function error: 'name'. Lambda request id: 83fcc181-b4b5-4a6d-b035-4ea12eaa892e
Thu Feb 03 10:48:15 UTC 2022 : Method completed with status: 502

Lambda 代理集成肯定是开启的,所以event 不能为空...

非常感谢您的帮助。谢谢你:)

更新:添加 print(event) 后添加 CloudWatch 日志:

{'resource': '/dragons', 'path': '/dragons', 'httpMethod': 'POST', 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'CloudFront-Forwarded-Proto': 'https', 'CloudFront-Is-Desktop-Viewer': 'true', 'CloudFront-Is-Mobile-Viewer': 'false', 'CloudFront-Is-SmartTV-Viewer': 'false', 'CloudFront-Is-Tablet-Viewer': 'false', 'CloudFront-Viewer-Country': 'UA', 'Content-Type': 'application/json', 'Host': 'HOST.execute-api.us-east-1.amazonaws.com', 'Postman-Token': 'b63589cf-40dc-43bb-bc16-37a4044170ef', 'User-Agent': 'PostmanRuntime/7.29.0', 'Via': '1.1 HOST.cloudfront.net (CloudFront)', 'X-Amz-Cf-Id': '==', 'X-Amzn-Trace-Id': 'Root=', 'X-Forwarded-For': '91.208.153.1, 54.239.171.73', 'X-Forwarded-Port': '443', 'X-Forwarded-Proto': 'https'}, 'multiValueHeaders': {'Accept': ['*/*'], 'Accept-Encoding': ['gzip, deflate, br'], 'CloudFront-Forwarded-Proto': ['https'], 'CloudFront-Is-Desktop-Viewer': ['true'], 'CloudFront-Is-Mobile-Viewer': ['false'], 'CloudFront-Is-SmartTV-Viewer': ['false'], 'CloudFront-Is-Tablet-Viewer': ['false'], 'CloudFront-Viewer-Country': ['UA'], 'Content-Type': ['application/json'], 'Host': ['HOST.execute-api.us-east-1.amazonaws.com'], 'Postman-Token': ['b63589cf-40dc-43bb-bc16-37a4044170ef'], 'User-Agent': ['PostmanRuntime/7.29.0'], 'Via': ['1.1 13182ff42379bbc1098730eb0992dbae.cloudfront.net (CloudFront)'], 'X-Amz-Cf-Id': ['Zv9A5svGpQsMHJl9JpF7I6E6lbCmrKnhuzJJtoGjaKnpNMMk4aibvg=='], 'X-Amzn-Trace-Id': ['Root='], 'X-Forwarded-For': ['91.208.153.1, 54.239.171.73'], 'X-Forwarded-Port': ['443'], 'X-Forwarded-Proto': ['https']}, 'queryStringParameters': None, 'multiValueQueryStringParameters': None, 'pathParameters': None, 'stageVariables': None, 'requestContext': {'resourceId': 'q5leiw', 'resourcePath': '/dragons', 'httpMethod': 'POST', 'extendedRequestId': 'M9nWSGX0IAMFW3g=', 'requestTime': '03/Feb/2022:11:13:56 +0000', 'path': '/Prod/dragons', 'accountId': '939694363734', 'protocol': 'HTTP/1.1', 'stage': 'Prod', 'domainPrefix': 'HOST', 'requestTimeEpoch': , 'requestId': '', 'identity': {'cognitoIdentityPoolId': None, 'accountId': None, 'cognitoIdentityId': None, 'caller': None, 'sourceIp': '91.208.153.1', 'principalOrgId': None, 'accessKey': None, 'cognitoAuthenticationType': None, 'cognitoAuthenticationProvider': None, 'userArn': None, 'userAgent': 'PostmanRuntime/7.29.0', 'user': None},  'body': '{\r\n    "name": "dragon",\r\n    "breed": "dragon",\r\n    "danger_rating": 6,\r\n    "description": "description"\r\n}', 'isBase64Encoded': False}

更新:我发现了新的有趣的东西 - 我在 API Gateway 中的请求正文的类型 - 字符串。为什么这样?如果我测试 Lambda - 一切正常,但 API Gateway 确实...

【问题讨论】:

  • 打印事件对象并检查传入的内容。您可以查看来自 CloudWatch 的日志
  • @HussainMansoor 我更新了这个问题。据我了解,一切似乎都很好。我以前从未使用过 CloudWatch

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


【解决方案1】:

正如我之前注意到的,API Gateway 将请求正文作为字符串,而不是 JSON。

我刚刚添加了json.loads(event['body'])。就是这样:)

听起来像是一个丑陋的黑客,无论如何。如果您知道更好的解决方案,请写信给我。

谢谢大家;)

你也可以在这里找到更好的解释:Getting json body in aws Lambda via API gateway

【讨论】:

    【解决方案2】:

    根据您共享的日志,名称键不直接位于事件对象下。您必须通过以下方式获得价值:

    table.put_item(
            Item={
                'name': event['body']['name']
                .
                .
            }
        )
    

    【讨论】:

    • Thu Feb 03 11:36:32 UTC 2022 : Endpoint response body before transformations: {"errorMessage": "string indices must be integers", "errorType": "TypeError", "requestId": "888f419c-18da-42a0-8277-a13f5e9719b9", "stackTrace": [" File \"/var/task/post_dragons.py\", line 15, in lambda_handler\n 'name': event['body']['name'],\n"]} Thu Feb 03 11:36:32 UTC 2022 : Lambda execution failed with status 200 due to customer function error: string indices must be integers. Lambda request id: 888f419c-18da-42a0-8277-a13f5e9719b9 Thu Feb 03 11:36:32 UTC 2022 : Method completed with status: 502
    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 2020-09-29
    • 1970-01-01
    • 2019-05-11
    • 2019-02-12
    • 2018-07-12
    • 2019-09-16
    • 2019-07-17
    相关资源
    最近更新 更多