How to capture botocore's NoSuchKey exception?

后端 未结 4 1396
时光说笑
时光说笑 2021-01-30 15:37

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\'         


        
4条回答
  •  长情又很酷
    2021-01-30 16:11

    I think the most elegant way to do this is in Boto3 is

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

    The documentation on error handling seems sparse, but the following prints the error codes this works for:

    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 object at 0x105e08c50 > object has no attribute 'InvalidBucketName'. Valid exceptions are: BucketAlreadyExists, BucketAlreadyOwnedByYou, NoSuchBucket, NoSuchKey, NoSuchUpload, ObjectAlreadyInActiveTierError, ObjectNotInActiveTierError

提交回复
热议问题