除了 IOLoop add_timeout 回调函数中的异常

Except exception in IOLoop add_timeout callback function

所以我正在使用

安排回调

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.

如果 callback_func 是您自己的代码,那么 到目前为止 捕获所有异常的最简单方法是简单地将整个函数体包装在 try / except 中:

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

它很简单,每个阅读你的代码的人都会理解它,不足为奇。

如果你想做一些奇特的和特定于 Tornado 的事情,请使用 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 Coroutines and the Tornado guide.