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()很适用于事务处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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