龙卷风:从未检索到任务异常

Tornado: Task exception was never retrieved

我在 Tornado WebSocket 服务器中遇到异常,但它在跟踪中没有提供任何信息来了解它来自我程序的哪一行代码或哪一步。我想找出答案,以便尝试捕获异常的来源。

错误跟踪:(未提及我文件的任何部分)

[E 200527 21:07:19 base_events:1608] Task exception was never retrieved
    future: <Task finished coro=<WebSocketProtocol13.write_message.<locals>.wrapper() done, defined at /usr/local/lib/python3.7/site-packages/tornado/websocket.py:1102> exception=WebSocketClosedError()>
    Traceback (most recent call last):
    File "/usr/local/lib/python3.7/site-packages/tornado/websocket.py", line 1104, in wrapper
        await fut
    tornado.iostream.StreamClosedError: Stream is closed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
    File "/usr/local/lib/python3.7/site-packages/tornado/websocket.py", line 1106, in wrapper
        raise WebSocketClosedError()
    tornado.websocket.WebSocketClosedError

[E 200527 21:07:19 base_events:1608] Task exception was never retrieved

同一组回溯重复超过 16 次。

这是我的代码:

import tornado.iostream
import tornado.web
import tornado.gen
import tornado.websocket
import asyncio

class SocketHandler(tornado.websocket.WebSocketHandler):
    waiters = set()
    def initialize(self):
        self.client_name = "newly_connected"

    def get_compression_options(self):
        # Non-None enables compression with default options.
        return {}

    def open(self):
        print('connection opened')
        # SocketHandler.waiters.add(self)

    def on_close(self):
        print("CLOSED!", self.client_name)
        try:
            SocketHandler.waiters.remove(self)
        except KeyError:
            print('tried removing new client')

    def check_origin(self, origin):
        # Override the origin check if needed
        return True

    @classmethod
    async def send_updates(cls, message):
        if len(cls.waiters) < 2:
            while True:
                chat = {}
                # Prevent RuntimeError: Set changed size during iteration
                waiters_copy = cls.waiters.copy()
                for waiter in waiters_copy:
                    try:
                        await waiter.write_message(chat)
                    except tornado.websocket.WebSocketClosedError:
                        pass
                    except tornado.iostream.StreamClosedError:
                        pass
                    except Exception as e:
                        print('Exception e:', waiter.client_name)
                        pass

                # sleep a bit
                await asyncio.sleep(0.05)
        else:
            print('broadcast loop already running')

    async def on_message(self, message):
        print("RECEIVED :", message)
        self.client_name = message
        self.first_serve_cache_on_connnect()
        SocketHandler.waiters.add(self)
        await SocketHandler.send_updates(message)

    def first_serve_cache_on_connnect(self):
        print('serving cache on connect')
        temp_calc_results = self.namespace.results
        try:
            self.write_message(temp_calc_results)
        except Exception as e:
            pass

我已经尝试在向 websocket 客户端发送消息时捕获可能导致任何错误的异常,但是当客户端连接到服务器时仍然会发生此错误。

消息 "task exception was never retrieved" 不是关于丢失的 try/except 块,而是关于丢失的 await。在 first_serve_cache_on_connect 中,您在没有 await 的情况下调用 write_message,因此在引发异常时 first_serve_cache_on_connect 不再是 运行,它无处可去,但日志。

这基本上是无害的,但是如果你想清理你的日志,你需要使first_serve_cache_on_connect成为一个async def协程,在[=19=中用await调用它],然后用 await 调用 write_message