简体   繁体   English

boto3 S3:get_object 错误处理

[英]boto3 S3: get_object error handling

What is the best way to do error handling when getting an object from S3 using Python boto3?使用 Python boto3 从 S3 获取对象时进行错误处理的最佳方法是什么?

My approach:我的做法:

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

I am not sure if ClientError is the best Exception to use here.我不确定 ClientError 是否是此处使用的最佳异常。 I know there is a Boto3Error class, but I do not think you can do error code checks similarly to ClientError.我知道有一个 Boto3Error 类,但我认为您不能像 ClientError 那样进行错误代码检查。

I think your approach is sufficient.我认为你的方法已经足够了。 If you can narrow your errors to a few, you can break it down into if blocks, and handle accordingly.如果您可以将错误缩小到几个,则可以将其分解为if块,并进行相应处理。

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

This is just an experimental approach.这只是一种实验方法。 Because most error responses are API-driven, I don't think you'll find them anywhere directly in the code (ie: doing except AccessDenied: ).因为大多数错误响应都是 API 驱动的,我认为您不会直接在代码中的任何地方找到它们(即: except AccessDenied:其他地方)。 You can find all error responses for Amazon S3 here.您可以在此处找到Amazon S3 的所有错误响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM