Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boto3 S3: get_object error handling

What is the best way to do error handling when getting an object from S3 using Python boto3?

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. I know there is a Boto3Error class, but I do not think you can do error code checks similarly to ClientError.

like image 587
JHuynnnh Avatar asked Oct 21 '17 00:10

JHuynnnh


1 Answers

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.

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:). You can find all error responses for Amazon S3 here.

like image 51
Mangohero1 Avatar answered Sep 28 '22 09:09

Mangohero1