Handle errors in Amazon API Gateway from integrated Lambda functions

In this blog, I am going to show how your API Gateway REST API behaves whenever a Lambda function which is integrated to it, returns an error. You will also learn how to handle those errors by mapping them to a corresponding HTTP status code as per your business requirement and use case.

Types of Lambda Integration

Before going ahead with the demo or setup, I would like to tell you about the two types of Lambda integration supported in API Gateway.

Proxy integration - The client sends a request to the API Gateway which acts as a proxy server, sends the entire request to its backend Lambda function. The integration method should be set as HTTP POST with the ARN of your Lambda function. Also, note that API Gateway should be granted with sufficient permission to invoke the function.

Non-proxy/Custom integration - Here the request received and response send by the API Gateway can be customized as per the requirement of the use case using Mapping templates and Models.

Handling of Lambda errors

For custom integration, the error returned by your function should be mapped properly to a standard HTTP status code which is apprehended by the clients.


Creating the function


In my example, I have a created a Lambda function that returns a standard exception randomly:
import json
import random

def lambda_handler(event, context):
    if random.choice([True, False]):
        raise Exception('Dummy error ...')
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

The output of the Lambda function when the code flow doesn't reach the 'if' block -
{
  "statusCode": 200,
  "body": "\"Hello from Lambda!\""
}

Whenever random.choice() method returns True, the flow enters the 'if' block throwing an exception -
{
  "errorMessage": "Dummy error ...",
  "errorType": "Exception",
  "requestId": "abcd1234-abb9-4ca3-b848-993693f465ab",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 6, in lambda_handler
    \nraise Exception('Dummy error ...')\n"
  ]
}

Creating the REST API

I have created a REST API with a resource - GET /lambda which is integrated to my above function.

Here is a snapshot of the API that I have created. Kindly note the Lambda proxy integration settings that can be enabled by marking the checkbox in the API Gateway console -




Results with -

A. Lambda proxy integration

1. The outputs observed on invoking the API and the function returned a successful message -

2. The output when the function returned an error -



This error code 502 is returned by the API Gateway as it is unable to apprehend the message returned by the Lambda function to it.

B. Lambda custom integration

1. When the function returned a successful message, here is the output on invoking the REST API -

Compare the results with A.1 where only the content of the body returned by the function was returned to the client. Whereas in this case the entire JSON response is returned.

2. Also, when the function has thrown an exception, despite the error message is returned the status code that the client would receive is 200 OK.


Important Note:

API Gateway matches the errorMessage returned by Lambda in the Integration Response, against the regex pattern configured. If there is a match then Lambda error is sent to the client along with the HTTP status code mapped else it goes along with the default response and status code(200 generally). In case there is no default response configured, the service throws an error.

Mapping the Lambda error

For an instance, I have decided to map the above error returned by my custom integrated function to HTTP status code 501. I need to add the status code in my API's Method Response in the following manner -


Add an Integration Response with Lambda error regex as 'Dummy error.*' which would be present in the errorMessage key of the response returned by the function. This expressed is mapped to the status code 501.


On invoking the API, this is the output observed whenever the function throws the exception -



Key Learnings

  • You have got an understanding of Proxy and Non-proxy/Custom Lambda integration for API Gateway.

  • The behavior of the API response for both the setup when the function returns a normal response as well as error response.

  • Also, you got to know how a standard error returned by an integrated function can be mapped to an HTTP Status code on the basis of the errorMessage using Lambda error regex in the Method Response settings of your API.


References

  1. Set up Lambda proxy integrations in API Gateway - https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
  2. Set up Lambda custom integrations in API Gateway - https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-custom-integrations.html
  3. Handle Lambda errors in API Gateway - https://docs.aws.amazon.com/apigateway/latest/developerguide/handle-errors-in-lambda-integration.html

Note: Not endorsed by AWS, all my understanding and opinions.

Comments

Popular posts from this blog

Kubernetes: A Synopsis and Introduction

Kubernetes : Pod Communications, Deployments and ReplicaSets