API Gateway + Lambda无法处理异常

时间:2018-06-27 09:03:17

标签: python exception-handling aws-lambda aws-api-gateway

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

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

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

enter image description here

我还定义了“ Lambda错误正则表达式”和“身体映射模板”。

enter image description here

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

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

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。

这是我的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'.*