Error handling in AWS API Gateway with Lambda

pahud
2 min readMar 7, 2016

--

When it comes to error handling in AWS API Gateway with Lambda, you may find this blog very informative. After some hours of experiments I am writing this blog to document the essential part of the whole story.

Let’s see if our Lambda is throwing error like this:

By default, you will get the http 200 with the body like this:


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

However, this may not be our expected response. If you need to make it http 400 Bad Request and just display the JSON value of the errorMessage, take the following steps:

1. create a Method Response with HTTP Status 400

2. Add an Integration Response

Enter the Error Regex as .*status.*fail.* and associate it to previously defined 400 status code. Please be noted if you set the regex as .*errorMessage.* it’s not gonna work. Always match the regex pattern to the value of errorMessage.

3. configure the Mapping Template

Configure the mapping template as the following. This will set $inputRoot(the input root node) as errorMessage, and then just display the whole object/value of it.

4. Deploy API

Remember to click Deploy API blue button, and try it with curl or postman you should be able to get your 400 error response with the payload as you expect.

--

--