Interview Prep/Python for DevOps/boto3 & AWS automation

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.

All Python for DevOps questions Roadmap: Python for automation

More on boto3 & AWS automation