Với mã như đoạn dưới đây, chúng ta có thể bắt ngoại lệ AWS:Bắt boto3 ClientError lớp con
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
Lỗi được thông báo là loại botocore.errorfactory.NoSuchEntityException
. Tuy nhiên, khi tôi cố gắng nhập ngoại lệ này, tôi có được điều này:
>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException
Phương pháp tốt nhất tôi có thể tìm bắt lỗi cụ thể này là:
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
Nhưng điều này có vẻ rất "hackish". Có cách nào để nhập trực tiếp và nắm bắt các lớp con cụ thể của ClientError
trong boto3 không?
EDIT: Lưu ý rằng nếu bạn gặp lỗi theo cách thứ hai và in loại, nó sẽ là ClientError
.