2015-09-19 31 views
0

所以我安排使用除IOLoop add_timeout回調函數的異常

ioloop.IOLoop.instance().add_timeout(time, callback_func)

但我callback_func可能拋出Exception,我要趕一個回調。

嘗試了什麼建議this answer但似乎沒有工作。或者,也許我沒有按照正確的方式去做。任何對此的幫助都會很大。

代碼是有點像這樣:

start.py

class Start: 
    # ... other methods ... 
    @staticmethod 
    def initialize(): 
     OtherClass.initialize() 

def main(): 
    Start.initialize() 

if __name__ == "__main__": 
    main() 

ioloop.IOLoop.instance().start() 

other_class.py

class OtherClass: 
    @staticmethod 
    def initialize(): 
     ioloop.IOLoop.instance().add_timeout(time, callback_func) 

    @staticmethod 
    def callback_func(): 
     # Need to catch any exception which occurs here. 

回答

1

如果callback_func是你自己的代碼,然後迄今爲止捕獲所有異常的最簡單方法t這裏是/簡單地包裹整個函數體中嘗試不同的:

@staticmethod 
def callback_func(): 
    try: 
     # ... your code ... 
    except Exception as exc: 
     # handle it 

很簡單,大家誰讀你的代碼將明白,沒有驚喜。

如果你想要做的事異國情調和旋風專用,使用ExceptionStackContext:

from tornado import ioloop 
from tornado.stack_context import ExceptionStackContext 


class OtherClass: 
    @staticmethod 
    def initialize(): 
     ioloop.IOLoop.instance().add_timeout(1, OtherClass.callback_func) 

    @staticmethod 
    def callback_func(): 
     # Need to catch any exception which occurs here. 
     1/0 

class Start: 
    # ... other methods ... 
    @staticmethod 
    def initialize(): 
     with ExceptionStackContext(Start.handler): 
      OtherClass.initialize() 

    @staticmethod 
    def handler(exc_type, exc_value, exc_traceback): 
     print("Caught %r in Handler" % exc_type) 
     return True # Tell Tornado that we handled it. 

def main(): 
    Start.initialize() 

if __name__ == "__main__": 
    main() 

ioloop.IOLoop.instance().start() 

最重要的是,使用協程,而不是回調。協程和回調一樣高效,但給你定期的Python異常處理語義。看到我的文章Refactoring Tornado CoroutinesTornado guide

+0

是的異常處理可以在回調函數本身完成,但那不是我正在尋找的。它在許多其他地方以這種方式完成,我希望在普通調用方類「Start」中放置一個可能的解決方案,這樣我就不必爲完整的回調代碼放置'try except'或將其他文件放在其他文件中從類似回調的'Start'調用。 – PratPor

+0

您的解決方案運行良好,並且如預期的那樣。謝謝。但是能不能有更通用的解決方案,可以應用於'Start'類的基礎上。 – PratPor

+0

編輯我的答案 - 我現在說明如何將處理程序移入Start類,並使用Start.initialize中的ExceptionStackContext而不是OtherClass.initialize。 –