2017-10-21 185 views
1

使用Python boto3從S3獲取對象時執行錯誤處理的最佳方式是什麼?boto3 S3:get_object錯誤處理

我的方法:

from botocore.exceptions import ClientError 
import boto3 

s3_client = boto3.client('s3') 

try: 
    s3_object = s3_client.get_object("MY_BUCKET", "MY_KEY") 
except ClientError, e: 
    error_code = e.response["Error"]["Code"] 
    # do error code checks here 

我不知道,如果是ClientError用在這裏最好的例外。我知道有一個Boto3Error類,但我不認爲你可以做類似於ClientError的錯誤代碼檢查。

回答

0

我認爲你的方法已經足夠。如果您可以將錯誤縮小爲幾個,則可以將其分解爲if塊,並進行相應處理。

except ClientError as e: 
    error_code = e.response["Error"]["Code"] 
    if error_code == "AccessDenied": 
     # do code 
    elif error_code == "InvalidLocationConstraint": 
     # do more code 

這只是一種實驗方法。由於大多數錯誤響應都是API驅動的,我不認爲你會直接在代碼中找到它們(例如:except AccessDenied:)。您可以找到全部error responses for Amazon S3 here.