Service Level Error Handling in Boto3
Boto3 is the official AWS SDK for Python. The official documentation for boto3 can be found at https://boto3.amazonaws.com . In this blog, we will discuss how to implement error handling in boto3. https://boto3.amazonaws.com/v1/documentation/api/latest/guide/error-handling.html tell us about why error handling is important and how to determine what errors to catch. It also tells us how to catch exceptions related to the low-level client which is also known as the botocore library. Service level error handling is not discussed in many details though. In this article, we will focus on how to handle service-level errors.
How to determine the errors and exceptions for each AWS API
The error responses for each API for each of the AWS Service are available at AWS API Reference Documentation. Here is a pseudo-code on how to handle service level errors
import boto3
client = boto3.client(<service name>)
try:
<performsome actions/api calls >
except client.exceptions.<Name of the Error> as e:
<do something with the error>
Example Code for Service level error handling
We will take an API for one service and see how we can incorporate error handling for this service.
Amazon Route53 is a highly available and scalable cloud Domain Name System (DNS) web service. It supports Private Hosted Zones which facilitates the use of private DNS records resolvable only within one or more VPCs. When it comes to cross-account VPC association with a private hosted zone, one has to authorize it first. More details are available here. Once created it is always a good practice to delete VPC association authorization. AWS provides an API to delete the VPC association authorization. . If we look at the possible errors , we can see that one of the errors is VPCAssociationAuthorizationNotFound
. This occurs when one tries to delete a non-existent VPC association authorization. The next section provides an example code on how to handle this error. This script deletes VPC association authorization for all Private Hosted zone created in an AWS account.
import boto3
client = boto3.client("route53")
hostedzones = client.list_hosted_zones()["HostedZones"]
for hostedzone in hostedzones:
id = hostedzone["Id"]
hostedzone_obj = client.get_hosted_zone(Id=id)
vpcs = hostedzone_obj["VPCs"]
print("Hosted Zone {0} - {1}".format(id,hostedzone["Name"] ))
is_private = hostedzone_obj["HostedZone"]["Config"]["PrivateZone"]
if is_private is True:
for vpc in vpcs:
try:
response = client.delete_vpc_association_authorization(
HostedZoneId=id,
VPC={
'VPCRegion': vpc['VPCRegion'],
'VPCId': vpc['VPCId']
}
)
except client.exceptions.VPCAssociationAuthorizationNotFound as e:
print(e)
Well, that's it! I hope this has been helpful in understanding and creating python scripts using the boto3 library with error handling built-in!