在上下文管理器中捕获异常是可能的吗?
背景:get_data_from_remote_system()方法每隔5分钟连接到远程系统并获取数据。
有时网络会出现故障。
我想在30分钟内抑制异常消息。30分钟后,我希望看到异常。
我不想捕获所有异常。只有一些。在本例中为socket.timeout。
有没有一种方法可以编写一个联系人管理器来实现这一点,并且这个上下文管理器的结果用法如下所示?
with suppress_exception(exceptions=[socket.timeout], minutes=30):
get_data_from_remote_system()发布于 2018-10-30 23:18:28
是的,我不知道如果您在__exit__()中返回True,则不会引发异常。
现在suppress_exception()上下文管理器很简单:
class suppress_exception(object):
def __init__(self, exceptions_to_catch, minutes=30):
self.exceptions_to_catch = exceptions_to_catch
self.timedelta = datetime.timedelta(minutes=minutes)
code = sys._getframe().f_back.f_code
self.cache_key = 'suppress_exception_' + code.co_filename + str(sys._getframe().f_back.f_lineno)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
datetime_of_first_failure = cache.get(self.cache_key)
now = datetime.datetime.now()
if not type:
cache.delete(self.cache_key)
if datetime_of_first_failure:
logging.info('Fine again. First failure was %s. Duration (first failure until ok): %s' % (
datetime_of_first_failure, now - datetime_of_first_failure))
return
if not issubclass(type, self.exceptions_to_catch):
# Thils will raise an exception
return
if not datetime_of_first_failure:
cache.set(self.cache_key, now)
datetime_of_first_failure = now
log_method = logging.warn
if datetime_of_first_failure + self.timedelta > now:
log_method = logging.info
log_method('%s %s (datetime_of_first_failure=%s)' % (type.__name__, value, datetime_of_first_failure))
return Truehttps://stackoverflow.com/questions/53066452
复制相似问题