How to capture botocore's NoSuchKey exception? How to capture botocore's NoSuchKey exception? python python

How to capture botocore's NoSuchKey exception?


from botocore.exceptions import ClientErrortry:    response = self.client.get_object(Bucket=bucket, Key=key)    return json.loads(response["Body"].read())except ClientError as ex:    if ex.response['Error']['Code'] == 'NoSuchKey':        logger.info('No object found - returning empty')        return dict()    else:        raise


Using botocore 1.5, it looks like the client handle exposes the exception classes:

session = botocore.session.get_session()client = session.create_client('s3')try:    client.get_object(Bucket=BUCKET, Key=FILE)except client.exceptions.NoSuchKey as e:    print >> sys.stderr, "no such key in bucket"


In boto3, I was able to access the exception in resource's meta client.

import boto3s3 = boto3.resource('s3')s3_object = s3.Object(bucket_name, key)try:    content = s3_object.get()['Body'].read().decode('utf-8')except s3.meta.client.exceptions.NoSuchKey:    print("no such key in bucket")