LoginSignup
8
7

More than 5 years have passed since last update.

PythonでDynamoDBの例外処理をする。

Last updated at Posted at 2018-05-17

ソースコード

Main.py
from botocore.exceptions import ClientError
if __name__ == '__main__':
    try:
        table = boto3.resource('dynamodb').Table('TableName')

        # DynamoDBからのエラーが発生するコードをここに書く

    except ClientError as e:
        print(e)
        print(e.response['Error']['Message']) # エラーメッセージ
        print(e.response['Error']['Code'])    # エラーコード(Exceptionの種類を示す文字列)
        print(e.response['ResponseMetadata']['RequestId'])
        print(e.response['ResponseMetadata']['HTTPStatusCode']) # ステータスコード
        print(e.response['ResponseMetadata']['HTTPHeaders']['server'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['date'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['content-type'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['content-length'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['connection'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['x-amzn-requestid'])
        print(e.response['ResponseMetadata']['HTTPHeaders']['x-amz-crc32'])
        print(e.response['ResponseMetadata']['RetryAttempts'])

※S3にもエラーメッセージ、エラーコード、ステータスコードは使用できます。

実行結果(例)

※接続情報などは*****でマスキングしています。

An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :val
Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :val
ValidationException
****************
400
Server
Thu, 17 May 2018 03:58:39 GMT
application/x-amz-json-1.0
***
keep-alive
****************
*****
0

この記事を書いた理由

HTTPStatusCodeを取得するためにネットで検索した際、
下記のStackoverflowに英語で例外処理が書いてありましたが、見つけにくかったので。
https://stackoverflow.com/questions/33068055/boto3-python-and-how-to-handle-errors

付録:EclipseでPythonを書く際の便利なショートカットキー

Ctrl + 1
※「F1」ではなく「1」
Eclipseでコンパイルエラーが発生した時、
そのエラー箇所にカーソルを当ててこのショートカットを使うと
根本原因のソースコードにカーソルが当たったり、
解決策が表示され、クリックすると自動で修正してくれたりします。

8
7
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
8
7