1

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?

Javier
  • 2,752
  • 15
  • 30
user389955
  • 9,605
  • 14
  • 56
  • 98

1 Answers1

3

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, ...)
Javier
  • 2,752
  • 15
  • 30
J. Blackadar
  • 1,821
  • 1
  • 11
  • 18
  • Thanks J. Blackadar. what if ddb_get_item (table, ...) return from raise? how will handler() take care of the raise? should handler() wrap ddb_get_item in try-except as well?. – user389955 Aug 14 '18 at 19:52
  • J. Blackadar. and reading your code, looks like if I want to quit, I can just type raise in called function and in calling function. – user389955 Aug 14 '18 at 19:58
  • The calling function will raise the same exception you caught in the callable, and you'll have the opportunity to handle it from that function, or to print an error. To understand this, think of a convenience store purchase where the cashier made the incorrect change for your purchase. The customer raises an IncorrectChangeException, but the cashier cannot do anything about it because she can't open the register. She `raise`s the exception to the manager, who will get the IncorrectChangeException. The manager can then open the drawer with their key, apologize, etc. Same concept applies. – J. Blackadar Aug 14 '18 at 20:04
  • J. Blackadar, Oh, I see. so if the handler() raise, then it will quit at the raise. that is why when I raise ValueError, it quits. – user389955 Aug 14 '18 at 21:11
  • Right, if there is a fatal and uncaught runtime exception it will quit. – J. Blackadar Aug 15 '18 at 14:15