In order to send a custom error code from AWS API GW you should use response mapping template in integration response.
You basically define a regular expression for each status code you'd like to return from API GW.
Steps:
Using this configuration the HTTP return code returned by API GW to the client is the one matching the regular expression in "selectionPattern".
Finally I strongly suggest to use an API GW framework to handle these configuration, Serverless is a very good framework.
Using Servereless you can define a template as follows (serverless 0.5 snippet):
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}'
Then simply return a json object from your lambda, as in the following python snippet (you can use similar approach in nodejs):
def handler(event, context):
# Your function code ...
response = {
'status':400,
'error':{
'error_message' : 'your message',
'details' : 'your details'
}
}
return response
I hope this helps.
G.