LoginSignup
2
1

More than 3 years have passed since last update.

boto3のS3 NoSuchKeyエラーをキャッチする方法

Posted at

Pythonのboto3でS3オブジェクト取得時に、オブジェクトが存在しなかった場合 S3.Client.exceptions.NoSuchKey というエラーが発生するとboto3のドキュメントには書かれています。しかしこのエラーをPythonで具体的にどうキャッチすればよいのかわからなかったので、動かしてみて調べました。

get_objecthead_object でなぜか挙動が違ってました。

get_object

次の2パターンのコードでエラーをキャッチできました。

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しているのは、NoSuchKey以外のエラーがあるかもしれないので、念のためです。

head_object

次のコードでエラーをキャッチできました。

get_object のマネをして s3_client.exceptions.NoSuchKey を試してもできませんでした。

ClientErrorでのキャッチもCodeの文字列がなぜか get_object とは違います。

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
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1