Catching boto3 ClientError subclass

Question:

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.

Asked By: Daniel Kats

||

Answers:

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
Answered By: Mads Hartmann

If you’re using the resource you can catch the exceptions like this:

cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except cf.meta.client.exceptions.NoSuchEntityException:
    # ignore the target exception
    pass

This combines the earlier answer with the simple trick of using .meta.client to get from the higher-level resource to the lower-level client (source: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/clients.html#creating-clients).

  try:
      something 
 except client.exceptions.NoSuchEntityException:
      something

This worked for me

Answered By: Ranjeet Golkonda