如何正確處理 AWS API Gateway 的 Lambda Error Status

翻譯自原文 Error handling in AWS API Gateway with Lambdahtml

這篇文章會介紹如何設置 AWS API Gateway 正確處理 Lambda 返回的 HTTP 錯誤狀態碼。json

本文假設讀者已經知道如何利用 AWS API Gateway 和 Lambda 創建 REST API,詳細可參考 Create API Gateway API for Lambda Functionsapi

假設你的 Lambda function 錯誤處理以下:app

console.log('I am a AWS Lambda function');

exports.handler = function(event, context) {
    // 通常使用 context.fail 來返回 Lambda function 錯誤
    context.fail(JSON.stringify({status:'fail', reason:'some reason', foo:'bar'}));
};

可是 API Gateway 返回的結果會是 HTTP 200ide

HTTP/1.1 200 OK
...

{
    "errorMessage": "{\"status\":\"fail\",\"reason\":\"some reason\",\"foo\":\"bar\"}"
}

我們但願的結果是:ui

  1. HTTP Status 400 Bad requestspa

  2. 只顯示 errorMessage 的 JSON 值code

1. 新增 HTTP Status 400 Method Response

  1. 前往 API Gateway Consolehtm

  2. 進入 Method Executionip

  3. 進入 Method Response

  4. 點選 Add Response

  5. 輸入 HTTP Status 400

  6. 點選 Add Response Model

  7. 輸入 Content type application/json、Models Error

enter image description here

2. 新增 Lambda Error Regex Integration Response

  1. 進入 Integration Response

  2. 點選 Add integration response

  3. 輸入 Lambda Error Regex .*status.*fail.*、Method response status 400

enter image description here

3. 設置 Mapping Templates

  1. 展開 Mapping Templates

  2. 點選 Add mapping template

  3. 輸入 Content-Type application/json

  4. 點選 Output passthrough 並改爲 Mapping Templates

  5. 輸入如下程式碼:

#set($inputRoot = $input.path('$.errorMessage'))
$inputRoot

enter image description here

4. 部署 API

記得點選 Deploy API 完成 API 的更新,然後測試返回結果是否為 HTTP 400

HTTP/1.1 400 Bad Request
...

{
    "foo": "bar",
    "reason": "some reason",
    "status": "fail"
}
相關文章
相關標籤/搜索