Skip to content

Instantly share code, notes, and snippets.

@g-io
Last active March 9, 2020 08:23
Show Gist options
  • Save g-io/b66a452be35fc3bb096e0e2ba971ec78 to your computer and use it in GitHub Desktop.
Save g-io/b66a452be35fc3bb096e0e2ba971ec78 to your computer and use it in GitHub Desktop.
Boto3 Exceptions List
List and use boto3 exceptions
# a handy one-liner for listing the exceptions
# of a specific AWS service, here s3
python3 -c 'import boto3; service="s3"; print(service.upper(), "\n", "\n".join(exc for exc in boto3.client(service).exceptions._code_to_exception), "\n", sep="")'
# and one to list them all
python3 -c 'import boto3; [print(service.upper(), "\n", "\n".join(exc for exc in boto3.client(service).exceptions._code_to_exception), "\n", sep="") for service in boto3.Session().get_available_services()]'
import botocore.exceptions
def hierarchy(t):
if t is Exception or t is object:
return t.__name__
result = t.__name__ + " < "
if len(t.__bases__) == 1:
result += hierarchy(t.__bases__[0])
else:
result += "[" + ", ".join([hierarchy(base) for base in t.__bases__]) + "]"
return result
# Getting the list of base exceptions/warnings
for key, value in sorted(botocore.exceptions.__dict__.items()):
if isinstance(value, type) and (value.__bases__ == (Exception,) or value.__bases__ == (Warning,)):
print(key)
# Printing the hierarchy
for key, value in sorted(botocore.exceptions.__dict__.items()):
if isinstance(value, type):
print(hierarchy(value))
import boto3
import uuid
# The Exceptions' hierarchy location is the client's exception package
s3 = boto3.client("s3")
bucket_name = "my-exception-test-bucket-" + uuid.uuid4()
s3.create_bucket(Bucket=bucket_name)
try:
s3.create_bucket(Bucket=bucket_name)
except s3.exceptions.BucketAlreadyExists as exc:
print("What a surprise! Bucket already exists!", exc)
s3.delete_bucket(Bucket=bucket_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment