2017-04-11 49 views
6

随着像下面的代码片段,我们可以赶上AWS例外:追赶boto3 ClientError子

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 

返回的错误是botocore.errorfactory.NoSuchEntityException类型。然而,当我尝试导入这个例外,我得到这个:

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

我能找到追赶此特定错误的最好方法是:

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 

但这似乎非常“的hackish”。有没有办法在boto3中直接导入并捕获ClientError的特定子类?

编辑:请注意,如果您在第二种方式捕获错误并打印类型,它将是ClientError

回答

7

如果您正在使用的client你能赶上这样的例外:

import boto3 

def exists(role_name): 
    client = boto3.client('iam') 
    try: 
     client.get_role(RoleName='foo') 
     return True 
    except client.exceptions.NoSuchEntityException: 
     return False 
1

如果您正在使用的resource你能赶上这样的例外:

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

这样就结合先前的答案是使用.meta.client从较高级别资源获取到较低级别客户的简单技巧。