在ContextManager中捕获异常?

2024-03-27 18:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以在上下文管理器中捕获异常?你知道吗

背景:方法get_data_from_remote_system()每五分钟连接一个远程系统并获取数据。你知道吗

有时网络瘫痪了。你知道吗

我想将异常消息抑制30分钟。30分钟后我想看看例外情况。你知道吗

我不想抓住所有的例外。只是一些。在这种情况下socket.timeout。你知道吗

有没有一种方法可以编写一个联系人管理器来实现这一点,而这个上下文管理器的最终用法是这样的?你知道吗

with suppress_exception(exceptions=[socket.timeout], minutes=30):
    get_data_from_remote_system()

Tags: 方法from网络消息管理器dataget远程
1条回答
网友
1楼 · 发布于 2024-03-27 18:00:47

是的,我不知道如果在__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 True

相关问题 更多 >