Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 961
Daniel Kats Avatar asked Apr 11 '17 18:04

Daniel Kats


2 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 
like image 136
Mads Hartmann Avatar answered Oct 02 '22 20:10

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

like image 23
MarnixKlooster ReinstateMonica Avatar answered Oct 02 '22 19:10

MarnixKlooster ReinstateMonica