通过 AWS API HTTP 网关从 AWS Lambda 返回错误消息

Return the error message from AWS Lambda through AWS API HTTP Gateway

提问人:Medical physicist 提问时间:11/17/2023 更新时间:11/17/2023 访问量:38

问:

我有一个与 AWS Lambda 集成的 Amazon API HTTP 网关。在某些情况下,lambda 可能会返回带有错误消息的错误。在这些情况下,我希望 API 返回 lambda 错误而不是 .Lambda 错误的格式为:Status 500, {"message": "Internal Server Error"}

{
  "errorMessage": "Error message of the lambda",
  "errorType": "lambda_failure",
  "stackTrace": [...]
}

如何更改积分响应以获取?Status 500, {"error": "Error message of the lambda"}

亚马逊网络服务 aws-lambda aws-api-gateway

评论


答:

1赞 tonystrawberry 11/17/2023 #1

您可以通过在 Lambda 中返回具有以下格式的对象来从 Lambda 返回错误。

{
  "isBase64Encoded" : "boolean",
  "statusCode": "number", // Represents the HTTP status code
  "headers": { ... }, // Represents the response headers
  "body": "JSON string" // Represents the body of the response
}

例如,如果您希望 API Gateway(由 AWS Lambda 支持)发送 404 (Not Found) 错误,则应在 Lambda 函数中按如下方式返回:

# Below is a Ruby code

return {
  statusCode: 500,
  body: {
    message: "An error occurred"
  }.to_json
}

参考资料: https://docs.aws.amazon.com/apigateway/latest/developerguide/handle-errors-in-lambda-integration.html

评论

0赞 Medical physicist 11/18/2023
谢谢,我知道这个选项。但我宁愿改变集成响应。