save_and_reraise_exception介绍 暂存异
2017-07-20 本文已影响12人
笨手笨脚越
有的时候突然抛出异常导致我们有些希望执行的关键程序没能执行,我们希望让异常延迟一些时候执行,好让我们关键程序跑完。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()
很适用于事务处理。