Skip to content Skip to sidebar Skip to footer

Catching Boto3 ClientError Subclass

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:

Solution 1:

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

Solution 2:

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).


Solution 3:

  try:
      something 
 except client.exceptions.NoSuchEntityException:
      something

This worked for me


Post a Comment for "Catching Boto3 ClientError Subclass"