pypiamazon-web-services95% confidence\u2191 33

Catching boto3 ClientError subclass

Full error message
With code like the snippet below, we can catch AWS exceptions:

from aws_utils import make_session

session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except Exception as e:
    print(type(e))
    raise e

The returned error is of type botocore.errorfactory.NoSuchEntityException. However, when I try to import this exception, I get this:

>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException

The best method I could find of catching this specific error is:

from botocore.exceptions import ClientError
session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except ClientError as e:
    if e.response["Error"]["Code"] == "NoSuchEntity":
        # ignore the target exception
        pass
    else:
        # this is not the exception we are looking for
        raise e

But this seems very "hackish". Is there a way to directly import and catch specific subclasses of ClientError in boto3?

EDIT: Note that if you catch errors in the second way and print the type, it will be ClientError.

If you're using the client you can catch the exceptions like this: import boto3 def exists(role_name): client = boto3.client('iam') try: client.get_role(RoleName='foo') return True except client.exceptions.NoSuchEntityException: return False

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/2d612e84e3c4a9418854fbf6b4af72b915ce33564df296875e050e0eb5a0c4ea
hash \u00b7 2d612e84e3c4a9418854fbf6b4af72b915ce33564df296875e050e0eb5a0c4ea
Catching boto3 ClientError subclass — DepScope fix | DepScope