如何捕获botocore的NoSuchKey异常?


102

我正在尝试编写“好”的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 *也不起作用,我也不想捕获一个通用错误。

Answers:


123
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

51

使用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"

我选择了这个,因为它比较新,也不太通用。您可以在GitHub上找到有关此方法的一些评论:github.com/boto/boto3/issues/1262#issuecomment-329314670
Sylwester Kardziejonek '18年

如果您忘了像我一样滚动:如果您正在使用高级资源(s3 = boto3.resource("s3")),则可以通过访问客户端,从而访问Exception s3.meta.client.exceptions.NoSuchKey。见stackoverflow.com/questions/38581465/...
lorey

31

在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")

24

我认为最完美的方式是在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)

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


由于可能不相关的原因,当我以这种方式捕获异常时,它们不会传播。(?)
Everett
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.