简体   繁体   中英

How to handle some exceptions in python

I have some knowledge of raise-exception, try-catch. but I am not clear how to handle these errors in a right way.

eg 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?

If you can handle an exception, then you should catch it, make the necessary modifications, then return to what you were doing. If your method is unable to handle the exception, you should raise the exception so that it is passed to the caller. Then, at the topmost calling method to your running instance, you should print a trace or error message if the exception is in fact fatal.

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'])
        raise
    else:
        return response['Item']

def handler (test):
    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))
            raise

 table = dynamodb.Table(table_name)
 ...
 response = ddb_put_item (table,...)
 item = ddb_get_item (table, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM