关于在Tornado的coroutine中正确捕获异常

具体说明参见: http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.coroutine

下面给出实际的例子:

# -*- coding:utf-8 -*-
'''
When exceptions occur inside a coroutine, the exception information will be stored in the Future object. 
You must examine the result of the Future object, or the exception may go unnoticed by your code. 
This means yielding the function if called from another coroutine, 
using something like IOLoop.run_sync for top-level calls, 
or passing the Future to IOLoop.add_future.
'''
from tornado import gen

from tornado.ioloop import IOLoop
import time
@gen.coroutine
def one():
    print('one entered' +  str( time.time() ) )
    yield gen.sleep(2)
    1 / 0
    #print('one leaving')
    return "one"

@gen.coroutine
def two():

    print('two entered' + str( time.time() ) )
    s = yield one()
    #print('one leaving')
    return "two "+ s

def _future_done(fu):
    pass
    fu.result()
@gen.coroutine    
def func_three():
    '''
      方案一: passing the Future to IOLoop.add_future.
    '''    
    print ("func_three ")
    a =   two()
    IOLoop.current().add_future(a, lambda x:x)
    result = yield a
    print ("THREE: " + result +  str( time.time() ) )
    pass

def func_sync_three():
    '''
      方案二: using something like IOLoop.run_sync for top-level calls, 
      !!!注意该函数不能被 @gen.coroutine覆盖!!! 否则无法捕获异常 。
    '''
    print ("func_sync ")
    result = IOLoop.current().run_sync(two)
    print ("SYNC: "+ result + str( time.time() ))
    pass

@gen.coroutine
def func_four_sync() :
    '''
      该方式不可行: 因为此时func_2rd不再是顶层调用
    '''
    func_sync_three()
    
@gen.coroutine
def func_four() :
    '''
      正确的处理异常的方式  调用链条:
      func_four (处理:在顶层函数捕获所有异常)-> 
      func_three()  (处理: add_future)->
      two -> (没有任何处理.... )
      one (抛出异常 )
    '''
    try:
        func_three()
        raise Exception("in func_four")
    except Exception as e:
        print ("ERROR:",e)

@gen.coroutine
def myself():
    '''
       因为自身也是 coroutine,所以自身的异常如果不手工处理则无法捕获。。。
    '''
    raise Exception(__name__)
    
if __name__ == '__main__':

    
    #func_first() # OK
    func_sync_three() 
    #func_four_sync() #不能捕获异常 
    #func_four() #能捕获one中的异常 , 
    IOLoop.current().start()


转载于:https://my.oschina.net/cppblog/blog/529700

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值