捕获boto3 ClientError子类

Dan*_*ats 17 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
Run Code Online (Sandbox Code Playgroud)

返回的错误是类型botocore.errorfactory.NoSuchEntityException.但是,当我尝试导入此异常时,我得到了这个:

>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException
Run Code Online (Sandbox Code Playgroud)

我能找到捕获此特定错误的最佳方法是:

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
Run Code Online (Sandbox Code Playgroud)

但这似乎非常"hackish".有没有办法直接导入和捕获ClientErrorboto3中的特定子类?

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

Mad*_*ann 23

如果您正在使用客户端,则可以捕获如下异常:

import boto3

def exists(role_name):
    client = boto3.client('iam')
    try:
        client.get_role(RoleName='foo')
        return True
    except client.exceptions.NoSuchEntityException:
        return False
Run Code Online (Sandbox Code Playgroud)


Mar*_*ica 10

如果您正在使用该资源,则可以捕获如下异常:

cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except cf.meta.client.exceptions.NoSuchEntityException:
    # ignore the target exception
    pass
Run Code Online (Sandbox Code Playgroud)

这将早期的答案与使用.meta.client从较高级别资源获取到较低级别客户端的简单技巧相结合.