爲了發送從AWS API GW一個自定義的錯誤代碼,您應該在合併響應使用響應映射模板。 您基本上爲每個想要從API GW返回的狀態代碼定義一個正則表達式。
步驟:
使用這種配置的HTTP返回代碼由API GW返回給客戶端是與「selectionPattern」中的正則表達式匹配的那個。
最後我強烈建議使用API GW框架來處理這些配置,Serverless是一個非常好的框架。
使用Servereless你如下(無服務器0.5片斷)可以定義模板:
myResponseTemplate:
application/json;charset=UTF-8: |
#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage'))) {
"status" : $errorMessageObj.status,
"error":{
"error_message":"$errorMessageObj.error.message",
"details":"$errorMessageObj.error.custom_message"
}
}
responsesValues:
'202':
selectionPattern: '.*"status": 202.*'
statusCode: '202'
responseParameters: {}
responseModels: {}
responseTemplates: '$${myResponseTemplate}'
'400':
selectionPattern: '.*"status": 400.*'
statusCode: '400'
responseParameters: {}
responseModels: {}
responseTemplates: '$${myResponseTemplate}'
然後簡單地從你的拉姆達返回一個JSON對象,如下面的Python代碼片段(可以使用類似方法nodejs):
def handler(event, context):
# Your function code ...
response = {
'status':400,
'error':{
'error_message' : 'your message',
'details' : 'your details'
}
}
return response
我希望這有助於。
G.
是http://stackoverflow.com/a/31371862/1428388有用嗎? – jbird