API 网关 + Lambda 未能处理异常

API Gateway + Lambda failed to handle exception

我有基于 Python 的 Lambda,它与 API 网关集成并尝试处理下面的 lambda 异常。

{
  "stackTrace": [
    [
      "/var/task/index.py",
      14,
      "handler",
      "raise Exception(err)"
    ]
  ],
  "errorType": "Exception",
  "errorMessage": "device name existed"
}

我已经为异常定义了方法响应的 HTTP 状态 400。

我还定义了"Lambda Error Regex"和"Body Mapping Templates"。

但是当我的 lambda 引发异常时,API 网关仍然响应 HTTP 状态 200 而不是 400。

任何人都知道出了什么问题。我错过了什么?

我自己找到了解决方案。

这是我的 Lambda 代码:

    raise Exception({
        "errorType" : "Exception",
        "httpStatus": 400,
        "message": err
    })

API 网关会得到类似

的错误
{
   "stackTrace": [["/var/task/index.py", 17, "handler", "\"message\": err"]], 
   "errorType": "Exception", 
   "errorMessage": "{'message': 'device not found', 'errorType': 'Exception', 'httpStatus': 400}"
}

我的 lambda 错误正则表达式不起作用的原因是错误消息在单引号而不是双引号内。

像下面这样更改 lambda 错误正则表达式后,一切正常

.*'errorType': 'Exception'.*