python - 捕获 boto3 ClientError 子类

标签 python amazon-web-services boto3

使用如下代码片段,我们可以捕获 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”。有没有办法在boto3中直接导入并捕获ClientError的特定子类?

编辑:请注意,如果您以第二种方式捕获错误并打印类型,它将是 ClientError

最佳答案

如果您使用的是 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

关于python - 捕获 boto3 ClientError 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43354059/

相关文章:

amazon-web-services - 当请求中未指定消息 SentTimestamp 时,Amazon Sqs 如何配置消息

amazon-web-services - NGINX 存储库中所需的 docker 镜像文件的完整路径

python - 如何使用 Boto3 (Python) 列出可用区域

python-3.x - 附加到 S3 中的文本文件

amazon-web-services - 使用 boto3 时如何创建具有自定义根卷大小的 aws 实例

python - Django,形式 is_valid() 始终为 false

python - 通过给定函数将点分配给对象

python - 无法从需要搜索输入的网站抓取 div 标签内的数据

java - AWS S3 Java SDK : RequestClientOptions. setReadLimit

python - 使用 Python 说明读取 API 结果