2017-04-11 45 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從較高級別資源獲取到較低級別客戶的簡單技巧。