How to capture botocore's NoSuchKey exception?

后端 未结 4 1394
时光说笑
时光说笑 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 15:59

    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
    

提交回复
热议问题