我正在尝试捕捉greenlets中引发的异常。根据本教程,不幸的是'Greenlet中提出的异常,留在Greenlet中'。在下面的代码中,我有一个同步方法,它会生成爬虫绿叶。那些爬虫会引发 HTTPError 异常,我需要在同步方法的主体中捕获它。基于异常,在sync方法中我会设置Account对象的相应状态。知道如何在同步方法中捕获 greenlets 中引发的异常以完成此操作吗?先感谢您!
# this is standalone helper method
def crawl(item):
try:
item.refresh_children(False) # THROWS HTTPError exception
greenlets = [gevent.spawn_link_exception(crawl, child) for child in item.children]
gevent.joinall(greenlets)
except HTTPError, e:
print e.message
raise e
except (JSONDecodeError, InvalidCredentialsException) as e:
print e.message
raise e
# this is instance method of the Account class
def sync(self):
"Sync search index with data from source"
try:
greenlets = [gevent.spawn_link_exception(crawl, item) for item in self.get_navigation()]
gevent.joinall(greenlets)
self.date_synced = datetime.datetime.now()
self.save()
except HTTPError, e:
if e.status_code == 401:
self.status = 'revoked'
else:
self.status = 'error'
self.save()
except LinkedFailed, e:
print e.message
exception_name = e.message.split()[-1]
if exception_name in ['HTTPError', 'JSONDecodeError']:
self.status = 'error'
self.save()
elif exception_name == 'InvalidCredentialsException':
self.status = 'revoked'
self.save()