How do you handle errors from boto3?
BeginnerConceptboto3 & AWS automation
Answer
Service errors raise botocore.exceptions.ClientError; inspect the code and HTTP status.
from botocore.exceptions import ClientError
try:
s3.head_bucket(Bucket=name)
except ClientError as e:
code = e.response["Error"]["Code"]
if code in ("404", "NoSuchBucket"):
create_bucket(name)
elif code in ("403", "AccessDenied"):
raise PermissionError(f"no access to {name}") from e
else:
raise
Modelled errors are also available as s3.exceptions.NoSuchKey etc. Client-side failures (no credentials, no region, connection errors) are subclasses of BotoCoreError, not ClientError.
More on boto3 & AWS automation
What is the difference between a boto3 Session, client and resource?BeginnerHow does boto3 find credentials?BeginnerHow does boto3 decide the region, and what is the gotcha with `AWS_REGION`?AdvancedWhy do you need paginators, and how do you use them?BeginnerWhat is JMESPath `search()` on paginators?AdvancedWhat are waiters, and why use them instead of `sleep` loops?Intermediate