0

When querying a DynamoDB table, the code works fine for a valid entry (msisdn) however, for non-existent entries it does crash.

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('PhoneList')

# Phone Number 
# -> Existent: 44790000000
msisdn = 44790000000

try:
    response = table.get_item(Key={'MSISDN': msisdn})
    
    name = response['Item']['Name']
    ID = str(response['Item']['ID'])
    birth = response['Item']['Birth']
    
except ClientError as e:
    print(e.response['Error']['Message'])
    print("Phone number not found")
    exit(-1)

print("Phone:", msisdn)
print("Name:", name)
print("ID:", id)
print("Birth:", birth)

Invalid Entry

Traceback (most recent call last):
  File "dyn.py", line 15, in <module>
    name = response['Item']['Name']
KeyError: 'Item'

Database

enter image description here

I think I might not handled correctly the Exception?

1 Answer 1

1

from the documentation

If there is no matching item, GetItem does not return any data and there will be no Item element in the response.

so you need to catch KeyError instead of ClientError.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.