This rule raises an issue when botocore.exceptions.ClientError can be thrown but is not explicitly caught and handled.

Why is this an issue?

AWS Lambda functions in Python use boto3, the AWS SDK, to communicate with other AWS services. boto3 operations can fail due to service-specific reasons like:

These errors are typically surfaced as botocore.exceptions.ClientError. Failing to handle these exceptions correctly by not catching them or using a broad try/except block can undermine the lambda function’s reliability and ease of debugging.

What is the potential impact?

Not catching and appropriately handling botocore.exceptions.ClientError in AWS Lambda functions can lead to:

How to fix

Lambda functions should explicitly catch botocore.exceptions.ClientError around boto3 calls. Inside the except block, e.response[‘Error’][‘Code’] should be inspected to determine the specific error and to be handled specifically.

Code examples

Noncompliant code example

import boto3

s3 = boto3.client("s3")

def lambda_handler(event, context):
    return s3.get_object(Bucket="my_bucket", Key="somefile.txt") # Noncompliant: No error handling, crash on missing file or permissions error

Compliant solution

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client("s3")

def lambda_handler(event, context):
    try:
        response = s3.get_object(Bucket="my_bucket", Key="somefile.txt")
    except ClientError as e: # Compliant: explicitly catching ClientError
        error_code = e.response['Error']['Code']
        if error_code == 'NoSuchKey':
            return {"error":"File not found"}
        elif ...:
          ...

Resources

Documentation