首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ContextManager中捕获异常?

在ContextManager中捕获异常?
EN

Stack Overflow用户
提问于 2018-10-30 22:23:12
回答 1查看 137关注 0票数 1

在上下文管理器中捕获异常是可能的吗?

背景:get_data_from_remote_system()方法每隔5分钟连接到远程系统并获取数据。

有时网络会出现故障。

我想在30分钟内抑制异常消息。30分钟后,我希望看到异常。

我不想捕获所有异常。只有一些。在本例中为socket.timeout

有没有一种方法可以编写一个联系人管理器来实现这一点,并且这个上下文管理器的结果用法如下所示?

代码语言:javascript
复制
with suppress_exception(exceptions=[socket.timeout], minutes=30):
    get_data_from_remote_system()
EN

回答 1

Stack Overflow用户

发布于 2018-10-30 23:18:28

是的,我不知道如果您在__exit__()中返回True,则不会引发异常。

现在suppress_exception()上下文管理器很简单:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53066452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档