在 API 网关中映射 Lambda 输出会导致服务器错误

Mapping Lambda output in API Gateway gives server error

我有一个 AWS API 网关设置,由 Python Lambda 函数提供服务。对于成功的响应,Lambda returns 形式的响应:

"200:{\"somekey\": \"somevalue\"}"

默认情况下,网关控制台中的 Integration Response 设置只有一个规则配置了 Lambda Error Regex of .* 映射到响应状态 200。这工作正常。

问题是当我尝试将其更改为 200.*(以启用更具体的代码时)。现在我得到一个

{"message": "Internal server error"}

每次我用 any 请求访问网关(结果是否为 200)。

没有错误日志写入 CloudWatch。

我想知道如何在 AWS API 网关中成功将 Lambda 输出映射到 HTTP 状态代码。

如果您在 API 网关中进行测试 运行,测试 运行 日志应显示类似于以下内容的错误:

Sat Nov 21 07:41:25 UTC 2015 : Execution failed due to configuration error: No match for output mapping and no default output mapping configured

问题是不再有捕捉成功响应的默认映射。错误正则表达式的目的是捕获错误并将它们映射到状态代码。错误正则表达式搜索失败的 json 响应的 errorMessage 属性。如果您将状态代码 400 设置为默认值(空白)- 您会发现您的成功响应始终映射到状态代码 400。

您最好保留 200 作为默认(空白)正则表达式。然后设置特定的正则表达式值来检查您的不同错误消息。例如,您可以有多个特定的错误正则表达式状态代码和一个通用的包罗万象的结果以产生 500。

对于那些在这个问题上尝试了所有方法却无法解决这个问题的人(比如我),请查看关于这个 post 的 thedevkit 评论(拯救了我的一天):

https://forums.aws.amazon.com/thread.jspa?threadID=192918

完全转载如下:

I've had issues with this myself, and I believe that the newline characters are the culprit.

foo.* will match occurrences of "foo" followed by any characters EXCEPT newline. Typically this is solved by adding the '/s' flag, i.e. "foo.*/s", but the Lambda error regex doesn't seem to respect this.

As an alternative you can use something like: foo(.|\n)*