Catching boto3 ClientError subclass

Daniel Kats picture Daniel Kats · Apr 11, 2017 · Viewed 12.9k times · Source

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.

Answer

Mads Hartmann picture Mads Hartmann · Jun 3, 2017

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