How to capture botocore's NoSuchKey exception?

theist picture theist · Mar 23, 2017 · Viewed 30.9k times · Source

I'm trying to write "good" python and capture a S3 no such key error with this:

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

But NoSuchKey isn't defined and I can't trace it to the import I need to have it defined.

e.__class__ is botocore.errorfactory.NoSuchKey but from botocore.errorfactory import NoSuchKey gives an error and from botocore.errorfactory import * doesn't work either and I don't want to capture a generic error.

Answer

Jose Alban picture Jose Alban · Mar 23, 2017
from botocore.exceptions import ClientError

try:
    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