随着像下面的代码片段,我们可以赶上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
。