2017-04-11 2 views
6

을 boto3 잡기, 우리는 AWS 예외를 잡을 수 :ClientError 서브 클래스 아래의 조각과 같은 코드로

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이 같은 예외를 잡을 수 있습니다 사용하는 경우

답변

7

:

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

이 콤바인 : 당신은이 resource이 같은 예외를 잡을 수 있습니다 사용하는 경우

import boto3 

def exists(role_name): 
    client = boto3.client('iam') 
    try: 
     client.get_role(RoleName='foo') 
     return True 
    except client.exceptions.NoSuchEntityException: 
     return False 
1

더 높은 수준의 리소스에서 낮은 수준의 클라이언트로 이동하기 위해 .meta.client을 사용하는 간단한 트릭을 사용한 이전 답변.