I have some knowledge of raise-exception, try-catch. but I am not clear how to handle these errors in a right way.
e.g. I created some dymanodb functions in AWS lambda service:
def dynamodb_create_table (table_name, ...):
table = dynamodb.create_table (...)
table.wait_until_exists()
return table
def dyndmodb_get_item (table, ...):
try:
response = table.get_item(...)
except ClientError as e:
logger.error (e.response['Error']['Message'])
return #question: what should I do here
else:
return response['Item']
def handler (test):
table_name = test["table_name"]
if table_name not in ["test1", "test2"]:
raise ValueError('table_name is not correct')
dynamodb = boto3.resource('dynamodb')
try:
response = boto3.client('dynamodb').describe_table(...)
except ClientError as ce:
if ce.response['Error']['Code'] == 'ResourceNotFoundException':
logger.info("table not exists, so Create table")
ddb_create_table (table_name, partition_key, partition_key_type)
else:
logger.error("Unknown exception occurred while querying for the " + table_name + " table. Printing full error:" + str(ce.response))
return # question: what should I do here
table = dynamodb.Table(table_name)
...
response = ddb_put_item (table,...)
item = ddb_get_item (table, ...)
...
As you can see, sometimes try-except is in called-functions (like dyndmodb_get_item), sometimes the try-except is in calling-functions (handler).
if there is except. I want the lambda exits/stop. then should I exit from called-functions directly, or should I return sth. in called-functions, catch it in calling-function, and then let calling function to exit?
Besides, I found if I use some build-in exception such as ValueError, I do not even need to wrap ValueError with try. etc. if the value is wrong, the function exits. I think it is neat. but this link Manually raising (throwing) an exception in Python put ValueError in a try-except. Anyone know whether it is enough to simply call ValueError or should I wrap it in try-except?