【问题标题】:Catching boto3 ClientError subclass捕获 boto3 ClientError 子类
【发布时间】:2017-09-07 07:41:49
【问题描述】:

使用如下 sn-p 之类的代码,我们可以捕获 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

【问题讨论】:

    标签: python amazon-web-services boto3


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您使用的是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 从较高级别资源获取较低级别客户端的简单技巧(来源:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/clients.html#creating-clients)。

      【讨论】:

      • 有人可以解释一下,这是如何被except捕获的?与 errorfactory 不同的类如何映射到这个类?
      • 我不明白你的意思。此解决方案对您不起作用吗?或者您只是对如何它的工作原理感兴趣?
      【解决方案3】:
        try:
            something 
       except client.exceptions.NoSuchEntityException:
            something
      

      这对我有用

      【讨论】:

      • 这是第一个被接受的答案的副本。还是我错过了什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多