我试图捕捉在greenlet中引发的异常。根据本教程,不幸的是"在Greenlet中引发的异常,留在Greenlet中"。在下面的代码中,我有一个同步方法,它产生爬行greenlet。那些抓取greenlet引发HTTPError异常,我需要在同步方法的主体中捕获。基于异常,我将在sync方法中设置Account对象的适当状态。我怎么能捕捉异常在同步方法中引发的greenlet为了实现这一点?提前感谢!
# 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()
greenlet将保存为greenlet生成的函数或异常(如果引发异常)的结果。您可以使用get
方法获得结果,或者重新引发异常。由于您似乎正在根据任何greenlet错误更改状态,因此同步方法最终看起来像这样:
def sync(self):
"Sync search index with data from source"
greenlets = [gevent.spawn_link_exception(crawl, item) for item in self.get_navigation()]
gevent.joinall(greenlets)
try:
results = [greenlet.get() for greenlet in greenlets]
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()
self.date_synced = datetime.datetime.now()
self.save()