利用 API Gateway API 处理 Lambda 错误 - AWS Lambda

利用 API Gateway API 处理 Lambda 错误

API Gateway 将所有调用和函数错误视为内部错误。如果 Lambda API 拒绝调用请求,API Gateway 会返回 500 错误代码。如果函数运行但返回错误,或返回格式错误的响应,API Gateway 会返回 502。在这两种情况下,来自 API Gateway 的响应的正文都是 {"message": "Internal server error"}

注意

API Gateway 不会重试 Lambda 调用。如果 Lambda 返回错误,API Gateway 会向客户端返回错误响应。

以下示例显示导致 API Gateway 中出现函数错误和 502 的请求的 X-Ray 跟踪映射。客户端收到通用错误消息。

使用 API Gateway 跟踪函数错误的映射。

要自定义错误响应,您必须捕获代码中的错误并以所需格式设置响应的格式。

index.mjs:格式设置错误
var formatError = function(error){ var response = { "statusCode": error.statusCode, "headers": { "Content-Type": "text/plain", "x-amzn-ErrorType": error.code }, "isBase64Encoded": false, "body": error.code + ": " + error.message } return response }

API Gateway 将此响应转换为带有自定义状态代码和正文的 HTTP 错误。在跟踪映射中,函数节点为绿色,因为它处理了错误。

使用 API Gateway 跟踪格式化错误的映射。