如何捕获botocore的NoSuchKey异常?

时间:2017-03-23 12:09:00

标签: python botocore

我正在努力写下#34;好" python并捕获S3没有这样的关键错误:

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"

但NoSuchKey尚未定义,我无法将其追踪到我需要定义的导入。

e.__class__botocore.errorfactory.NoSuchKeyfrom botocore.errorfactory import NoSuchKey出错,from botocore.errorfactory import *也无效,我也不想捕获一般错误。

4 个答案:

答案 0 :(得分:63)

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 ex

答案 1 :(得分:29)

使用botocore 1.5,看起来客户端句柄暴露了异常类:

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"

答案 2 :(得分:8)

我认为最优雅的方法是在Boto3中

session = botocore.session.get_session()
client = session.create_client('s3')

try:
    client.get_object(Bucket=BUCKET, Key=FILE)
except client.exceptions.NoSuchKey:
    print("no such key in bucket")

有关错误处理的文档似乎很少,但以下内容会打印出适用于的错误代码:

session = botocore.session.get_session()
client = session.create_client('s3')
try:
    try:
        client.get_object(Bucket=BUCKET, Key=FILE)
    except client.exceptions.InvalidBucketName:
        print("no such key in bucket")
except AttributeError as err:
    print(err)
  

< botocore.errorfactory.S3Exceptions对象位于0x105e08c50>对象没有属性' InvalidBucketName'。有效的例外有:BucketAlreadyExists,BucketAlreadyOwnedByYou,NoSuchBucket,NoSuchKey,NoSuchUpload,ObjectAlreadyInActiveTierError,ObjectNotInActiveTierError

答案 3 :(得分:7)

在boto3中,我能够访问资源的元客户端中的异常。

import boto3

s3 = 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")