save_and_reraise_exception介绍 暂存异常信息延迟抛出

有的时候突然抛出异常导致我们有些希望执行的关键程序没能执行,我们希望让异常延迟一些时候执行,好让我们关键程序跑完。oslo_utils工具包提供了save_and_reraise_exception这个工具类,很好的实现了这个功能。

oslo_utils.excutils.save_and_reraise_exception 源码:

class save_and_reraise_exception(object):
    """Save current exception, run some code and then re-raise.

    In some cases the exception context can be cleared, resulting in None
    being attempted to be re-raised after an exception handler is run. This
    can happen when eventlet switches greenthreads or when running an
    exception handler, code raises and catches an exception. In both
    cases the exception context will be cleared.

    To work around this, we save the exception state, run handler code, and
    then re-raise the original exception. If another exception occurs, the
    saved exception is logged and the new exception is re-raised.

    In some cases the caller may not want to re-raise the exception, and
    for those circumstances this context provides a reraise flag that
    can be used to suppress the exception.  For example::

      except Exception:
          with save_and_reraise_exception() as ctxt:
              decide_if_need_reraise()
              if not should_be_reraised:
                  ctxt.reraise = False

    If another exception occurs and reraise flag is False,
    the saved exception will not be logged.

    If the caller wants to raise new exception during exception handling
    he/she sets reraise to False initially with an ability to set it back to
    True if needed::

      except Exception:
          with save_and_reraise_exception(reraise=False) as ctxt:
              [if statements to determine whether to raise a new exception]
              # Not raising a new exception, so reraise
              ctxt.reraise = True

    .. versionchanged:: 1.4
       Added *logger* optional parameter.
    """
    def __init__(self, reraise=True, logger=None):
        self.reraise = reraise
        if logger is None:
            logger = logging.getLogger()
        self.logger = logger
        self.type_, self.value, self.tb = (None, None, None)

    def force_reraise(self):
        # 重新抛出异常
        if self.type_ is None and self.value is None:
            raise RuntimeError("There is no (currently) captured exception"
                               " to force the reraising of")
        six.reraise(self.type_, self.value, self.tb)

    def capture(self, check=True):
        # 抓取异常,并暂存信息
        (type_, value, tb) = sys.exc_info()
        if check and type_ is None and value is None:
            raise RuntimeError("There is no active exception to capture")
        self.type_, self.value, self.tb = (type_, value, tb)
        return self

    def __enter__(self):
        # with 语句的入口函数
        # TODO(harlowja): perhaps someday in the future turn check here
        # to true, because that is likely the desired intention, and doing
        # so ensures that people are actually using this correctly.
        return self.capture(check=False)

    def __exit__(self, exc_type, exc_val, exc_tb):
        # with 语句的出口函数, 这里调用force_reraise做重新抛出异常
        if exc_type is not None:
            if self.reraise:
                self.logger.error(_LE('Original exception being dropped: %s'),
                                  traceback.format_exception(self.type_,
                                                             self.value,
                                                             self.tb))
            return False
        if self.reraise:
            self.force_reraise()

测试demo:

from oslo_utils import excutils

def test1():
    a = [1,2,3,4]
    try:
        print '11111'
        print a[10]
        print '22222'
    except:
        with excutils.save_and_reraise_exception():
            print '3333'

if __name__ == '__main__':
    test1()


C:\Python27\python.exe D:/wangyueWorkspace/mytest/olsoutils/test1.py
Traceback (most recent call last):
  File "D:/wangyueWorkspace/mytest/olsoutils/test1.py", line 18, in <module>
    test1()
  File "D:/wangyueWorkspace/mytest/olsoutils/test1.py", line 13, in test1
    print a
  File "C:\Python27\lib\site-packages\oslo_utils\excutils.py", line 220, in __exit__
    self.force_reraise()
  File "C:\Python27\lib\site-packages\oslo_utils\excutils.py", line 196, in force_reraise
    six.reraise(self.type_, self.value, self.tb)
  File "D:/wangyueWorkspace/mytest/olsoutils/test1.py", line 7, in test1
    print a[10]
IndexError: list index out of range
11111
3333

Process finished with exit code 1

说明:
我定义a 数组有4个元素,所以在执行到print a[10]的时候会抛出下标越界的异常IndexError。捕获到这个异常后excutils.save_and_reraise_exception() 会把这个异常的一些信息,包括异常名字、异常消息、堆栈信息先暂存下来,然后运行print '3333',当with下的程序都执行完了,excutils.save_and_reraise_exception()才把之前暂存的错误重新抛出。


我们看看cinder里是怎么利用这个工具类的。cinder backup-create的代码里,创建过程中如果出错,就用save_and_reraise_exception做延迟抛出:

cinder.backup.api.API#create:

    try:
        <!--创建buckup的业务代码-->
    except Exception:
        with excutils.save_and_reraise_exception():
            try:
                # 销毁掉已经创建一半的backup
                if backup and 'id' in backup:
                    backup.destroy()
            finally:
                # 回退掉配额占用
                QUOTAS.rollback(context, reservations)

所以excutils.save_and_reraise_exception()很适用于事务处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,635评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,543评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,083评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,640评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,640评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,262评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,833评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,736评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,280评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,369评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,503评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,185评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,870评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,340评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,460评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,909评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,512评论 2 359

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,663评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 3,814评论 0 11
  • abstract 抽象的abstract base class (ABC)抽象基类abstract class...
    码蚁Q阅读 1,028评论 3 29
  • 一、说话一定要有自信 有了自信之后,我们在介绍产品的时候就可以做清楚的、强劲的结束,由此给客户一个确实的信息。比如...
    肖红千金阅读 256评论 0 0
  • 夜还是来临了,辗转不安,害怕梦的来扰。 夜不懂白天的光茫? 还是白天不懂夜的黑? 醉了,醉了!听着那平稳的呼吸声,...
    不舍_0e35阅读 283评论 0 0