使用下面的代码段代码,我们可以捕获AWS异常:
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”。有没有办法直接导入和捕获特定的子类 ClientError
在boto3?
编辑:请注意,如果您以第二种方式捕获错误并打印类型,它将是 ClientError
。