Catching boto3 ClientError subclass

后端 未结 3 1127
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 01:18

With code like the snippet below, we can catch AWS exceptions:

from aws_utils import make_session

session = make_session()
cf = session.resource(\"iam\")
ro         


        
相关标签:
3条回答
  • 2020-12-31 01:25

    If you're using the client you can catch the exceptions like this:

    import boto3
    
    def exists(role_name):
        client = boto3.client('iam')
        try:
            client.get_role(RoleName='foo')
            return True
        except client.exceptions.NoSuchEntityException:
            return False
    
    0 讨论(0)
  • 2020-12-31 01:27
      try:
          something 
     except client.exceptions.NoSuchEntityException:
          something
    

    This worked for me

    0 讨论(0)
  • 2020-12-31 01:41

    If you're using the resource you can catch the exceptions like this:

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

    This combines the earlier answer with the simple trick of using .meta.client to get from the higher-level resource to the lower-level client.

    0 讨论(0)
提交回复
热议问题