I can not catch the exception
from sanic import Sanic, Request, Websocket
from sanic.response import text
from sanic.exceptions import ServerError, WebsocketClosed
app = Sanic("xxx")
@app.websocket("/ws")
async def sanic_ws_handler(request: Request, ws: Websocket):
remote_address = (request.ip, request.port)
db_pool = request.app.ctx.db_pool
try:
while True:
logger.debug('waiting for message from {}', remote_address)
data = await ws.recv()
if data is None:
logger.debug('waiting for message from {} done, None',
remote_address)
continue
logger.debug('waiting for message from {} done, {} bytes',
remote_address, len(data))
result = await message_handler.dispatch(data, remote_address,
db_pool)
if result is not None:
await ws.send(result)
except WebsocketClosed as e:
logger.error("{} closed: {}", remote_address, e)
except Exception as e:
logger.error(f"{remote_address} exception: {e}")
finally:
try:
#
pass
except Exception as e:
logger.error('断开连接异常: {}', e)
app.run(host="0.0.0.0", port=18765, debug=False)
it sometimes throw exception
0 2025-07-30 21:55:31 +0800 ERROR: Error closing websocket connection
Traceback (most recent call last):
File "/home/xxx/venv/xxx/lib/python3.12/site-packages/sanic/server/websockets/impl.py", line 422, in auto_close_connection
self.io_proto.transport.write_eof()
File "uvloop/handles/stream.pyx", line 703, in uvloop.loop.UVStream.write_eof File "uvloop/handles/handle.pyx", line 159, in uvloop.loop.UVHandle._ensure_alive
RuntimeError: unable to perform operation on <TCPTransport closed=True reading=False 0x19d34520>; the handler is closed
env: ubuntu 2404, python 3.12.3
sanic 25.3.0
sanic-routing 23.12.0
uvloop 0.21.0
websockets 15.0.1