我将连接的应用程序逻辑全部包裹在一个大的 try/except/finally 块中:
async def serve(self, stream: trio.SocketStream):
try:
async with trio.open_nursery() as nursery:
pass # code goes here to do some reading and writing
except Exception as e:
print("Got exception:", e)
except trio.Cancelled:
print("Cancelled")
raise
# some other handlers, mostly just logging
finally:
# ... some other stuff ...
# ... then shut the connection:
with trio.move_on_after(1):
await stream.aclose()
我不清楚是否应该尝试在 finally 子句中关闭连接。如果异常是由于应用程序错误(来自连接的无效消息,或协程被取消),这似乎是正确的做法,但如果异常是连接从另一端关闭,那么这似乎适得其反 - 我期望旧的异常会被新的异常掩盖。有什么想法吗?我也许可以将它包装在自己的 try/except 中,而忽略任何异常。