LoginSignup
41
34

More than 5 years have passed since last update.

boto3の例外ハンドリング

Posted at

boto3を使ってるときに、存在しないS3のオブジェクトを読み込んだ時のエラーハンドリングがしたかった時に調べたことをメモ。

NoSuchKeyのエラーが返るけど、動的に生成される例外クラスのようで、インポートしてexcept節に記述できない。

stackoverflowに対応方法が書いてた。
http://stackoverflow.com/questions/33068055/boto3-python-and-how-to-handle-errors

以下、抜粋。

import boto3
from botocore.exceptions import ClientError

try:
    iam = boto3.client('iam')
    user = iam.create_user(UserName='fred')
    print "Created user: %s" % user
except ClientError as e:
    if e.response['Error']['Code'] == 'EntityAlreadyExists':
        print "User already exists"
    else:
        print "Unexpected error: %s" % e

botocore.exceptionsのClientErrorとして例外をキャッチして、response['Error']['Code']の値でエラー内容を確認する。

41
34
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
41
34