我对引发异常,尝试捕捉有一些了解。但我不清楚如何正确处理这些错误。
例如,我在AWS lambda服务中创建了一些dymanodb函数:
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, ...)
...
如您所见,有时try-except在调用函数中(例如dyndmodb_get_item),有时try-except在调用函数中(处理程序)。
如果有的话。我想让lambda退出/停止。那么我应该直接退出被调用函数,还是应该返回sth。在被调用函数中,将其捕获在调用函数中,然后让调用函数退出?
此外,我发现如果我使用一些内置异常(例如ValueError),我什至不需要用try来包装ValueError。等等。如果值错误,则函数退出。我认为这很整洁。但是此链接 在Python中手动引发(引发)异常 将ValueError放入try-except中。有人知道简单地调用ValueError是否足够,还是应该将其包装在try-except中?
相关分类