隨着像下面的代碼片段,我們可以趕上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
。