简体   繁体   English

如何处理python中的一些异常

[英]How to handle some exceptions in python

I have some knowledge of raise-exception, try-catch.我对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:例如,我在 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, ...)
 ...

As you can see, sometimes try-except is in called-functions (like dyndmodb_get_item), sometimes the try-except is in calling-functions (handler).如您所见,有时 try-except 位于被调用函数(如 dyndmodb_get_item)中,有时 try-except 位于调用函数(处理程序)中。

if there is except.如果有除外。 I want the lambda exits/stop.我想要 lambda 退出/停止。 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.此外,我发现如果我使用一些内置异常,例如 ValueError,我什至不需要用 try 包装 ValueError。 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.但是这个链接Manually raise (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?任何人都知道简单地调用 ValueError 是否就足够了,还是应该将其包装在 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.如果您的方法无法处理异常,您应该raise异常,以便将其传递给调用者。 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, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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