捕获boto3 Clienteror子类

2024-04-24 17:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下面的代码片段,我们可以捕获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

但这看起来很“老套”。有没有办法直接导入和捕获boto3中ClientError的特定子类?

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


Tags: fromimportmakefoosession错误resourceiam
3条回答
  try:
      something 
 except client.exceptions.NoSuchEntityException:
      something

这对我有效

如果您正在使用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

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

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

这将前面的答案与使用.meta.client从高级资源到低级客户机的简单技巧结合起来。

相关问题 更多 >