How to catch Boto3 errors
Catching errors with the boto3
library is straightfoward.
Catching boto3
errors with ClientError
1import boto3
2import botocore
3
4s3 = boto3.client("s3")
5
6try:
7 s3.get_object(Bucket="bucket", Key="key")
8except botocore.exceptions.ClientError as e:
9 if e.response["Error"]["Code"] == "AccessDenied":
10 print(e.response["Error"]["Message"])
11 else:
12 raise
Other information in the e.response
object may additionally be useful:
e.response["Error"]["Code"]
for the error codee.response["Error"]["Message"]
for the error messagee.response["ResponseMetadata"]["RequestId"]
for the request ide.response["ResponseMetadata"]["HTTPStatusCode"]
for the status code
e.response
’s full dictionary:
1{
2 'Error': {
3 'Code': 'AccessDenied',
4 'Message': 'Access Denied'
5 },
6 'ResponseMetadata': {
7 'RequestId': 'requestId',
8 'HostId': 'hostId',
9 'HTTPStatusCode': 403,
10 'HTTPHeaders': {
11 'x-amz-request-id': 'requestId',
12 'x-amz-id-2': 'id-2',
13 'content-type': 'application/xml',
14 'transfer-encoding': 'chunked',
15 'date': 'Sat, 04 Mar 2023 06:11:15 GMT',
16 'server': 'AmazonS3'
17 },
18 'RetryAttempts': 0
19 }
20}
Catching boto3
errors with service exceptions
For some clients, the AWS Python SDK has exposed service exceptions:
1import boto3
2import botocore
3
4s3 = boto3.client("s3")
5
6try:
7 s3.create_bucket(Bucket="bucket")
8except s3.exceptions.BucketAlreadyExists:
9 print("s3 bucket already exists")
10except botocore.exceptions.ClientError as e:
11 print(e)