这个问题来自生成器中的捕获错误,然后继续
我有大约 50 个类似(但不同)的函数,它们试图从网站中提取 URL 等。因为每个网站都是不同的,每个功能都是不同的,而且因为网站往往会随着时间的推移而改变,所以这个代码是混乱的,不能被信任。
这是一个简化的示例,或者看第一个问题中的示例
def _get_units(self):
for list1 in self.get_list1():
for list2 in self.get_list2(list1):
for unit in list2:
yield unit
我想用这个函数做的基本上是改变行为以匹配这个:
def _get_units(self):
for list1 in self.get_list1():
try:
for list2 in self.get_list2(list1):
try:
for unit in list2:
try:
yield unit
except Exception as e:
log_exception(e)
except Exception as e:
log_exception(e)
except Exception as e:
log_exception(e)
总之,我想把这个
for x in list:
do_stuff(x)
对此:
for x in list:
try:
do_stuff(x)
except Exception as e:
log_exception(e)
对于for
我的职能中的每一个。
但我想以pythonic的方式来做。我不希望try:except
块分散在我需要更改的 50 个函数中。这可能吗?如果是这样,我怎样才能以最干燥的方式做到这一点,我可以在一个地方进行错误处理吗?
更新:这个问题以前包括一个continue
与日志记录一起的语句,但正如 mgilson 指出的那样,这不是必需的。
使用georgesl的答案更新2,函数如下:
from contextlib import contextmanager
@contextmanager
def ErrorManaged():
try:
yield
except Exception as e:
log_exception(e)
def _get_units(self):
for list1 in self.get_list1():
with ErrorManaged():
for list2 in self.get_list2(list1):
with ErrorManaged():
for unit in list2:
with ErrorManaged():
yield unit
这确实更清洁。不过,单纯的装饰者会更好。谁能告诉我这是否可能?如果没有,我会接受georgesl的回答。