首页 > 解决方案 > Python在引发异常后添加重试

问题描述

我继承了一个需要一些返工的代码。频谱扫描错误不断发生,这是引发异常的地方:

try:
    # iterate trough each record in json file
    for i in sorted(tables_to_load, key=lambda x: (tables_to_load[x]["order"])):
        # print(i)
        # if table exclude flag is set to "N", proceed with load_table()
        if tables_to_load[i]["exclude"] == "N":
            try:
                job_start_time = datetime.now()
                logger.info("Begin load for: %s ---- %s ----" %(tables_to_load[i]["order"], i))
                error_code = load_table(i, tables_to_load[i], from_date, to_date, max_proc, dm_updated, 
                process_flag)
                job_end_time = datetime.now()
                job_duration = (job_end_time - job_start_time).total_seconds()
                logger.info("Load for table: %s -- time: %s seconds." %(i, job_duration))
            except Exception as e:
                #this is where the error is cought
                logger.error("Load for table: %s FAILED: %s" %(i, e))
                raise
        #else the table is excluded and we skip it
        else:
            logger.info("Table excluded from load: %s " %i)
except Exception as e:
    # upload error log to s3
    s3.upload_file(filepath + filename, s3_logbucket, s3_logprefix + filename)
    raise

基本上,该脚本读取一个 json cfg 文件,其中包含一个由 YYYYMMDD 或 YYYYMMDDhhmmss) 分区的外部表列表、RS 表和 RS 存储过程,它们将数据从 S3 加载到 RS。当错误被捕获时,我不希望引发错误。或者更确切地说,我想在引发错误之前给它 3 次。我需要帮助编写那个迭代吗?

谢谢,罗莎

标签: pythonamazon-web-servicesamazon-s3amazon-redshift

解决方案


如果您将重试策略设置为 3 次(异步调用部分下的重试尝试),则在引发异常时它将自动重试。如果您使用 SQS 或 Kinesis 触发 lambda 函数,它会确保重试 lambda。

如果您不需要继续该路线,您可以简单地修改您的代码以重试。

retries = 0
retry_limit = 3

while retries < retry_limit:
    try:
        # you code goes here
        break
    except Exception as e:
        # log the error
        retries += 1
        if retries == retry_limit:
            raise e

但是,我不建议这样做。原因是,lambda 的生命周期有限,手动重试会消耗它。

因此,尝试使第一个选项无效。


推荐阅读