The boto3 documentation states that when getting an S3 object in Python's boto3, the error S3.Client.exceptions.NoSuchKey
occurs if the object does not exist. However, I didn't know how to catch this error in Python, so I tried it and investigated it.
For some reason, the behavior of get_object
and head_object
was different.
get_object
I was able to catch the error with the following two patterns of code.
import boto3
s3_bucket = "..."
s3_key = "..."
session = boto3.session.Session()
s3_client = session.client("s3")
try:
s3_client.get_object(
Bucket = s3_bucket,
Key = s3_key,
)
except s3_client.exceptions.NoSuchKey as e:
"NOT FOUND ERROR!"
import boto3
import botocore.exceptions
s3_bucket = "..."
s3_key = "..."
session = boto3.session.Session()
s3_client = session.client("s3")
try:
s3_client.get_object(
Bucket = s3_bucket,
Key = s3_key,
)
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "NoSuchKey":
"NOT FOUND ERROR!"
else:
raise
raise
is just in case there may be an error other than NoSuchKey
.head_object
I was able to catch the error with the following code.
I couldn't even try s3_client.exceptions.NoSuchKey
by imitating get_object
.
The catch with ClientError
is also different from get_object
for some reason because the string of Code
is.
import boto3
import botocore.exceptions
s3_bucket = "..."
s3_key = "..."
session = boto3.session.Session()
s3_client = session.client("s3")
try:
s3_client.head_object(
Bucket = s3_bucket,
Key = s3_key,
)
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "404":
"NOT FOUND ERROR!"
else:
raise
$ pip list | grep boto
boto3 1.14.63
botocore 1.17.63
Recommended Posts