Skip to content

Commit 42db293

Browse files
kumaraditya303miss-islington
authored andcommitted
[3.12] pythonGH-110894: Call loop exception handler for exceptions in client_connected_cb (pythonGH-111601) (pythonGH-111632)
(cherry picked from commit 9aa8829) Co-authored-by: Kumar Aditya <[email protected]> Call loop exception handler for exceptions in `client_connected_cb` of `asyncio.start_server` so that applications can handle it.. (cherry picked from commit 229f44d)
1 parent cf61454 commit 42db293

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

Lib/asyncio/streams.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,19 @@ def connection_made(self, transport):
245245
res = self._client_connected_cb(reader,
246246
self._stream_writer)
247247
if coroutines.iscoroutine(res):
248+
def callback(task):
249+
exc = task.exception()
250+
if exc is not None:
251+
self._loop.call_exception_handler({
252+
'message': 'Unhandled exception in client_connected_cb',
253+
'exception': exc,
254+
'transport': transport,
255+
})
256+
transport.close()
257+
248258
self._task = self._loop.create_task(res)
259+
self._task.add_done_callback(callback)
260+
249261
self._strong_reader = None
250262

251263
def connection_lost(self, exc):

Lib/test/test_asyncio/test_streams.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,35 @@ def test_eof_feed_when_closing_writer(self):
10681068

10691069
self.assertEqual(messages, [])
10701070

1071+
def test_unhandled_exceptions(self) -> None:
1072+
port = socket_helper.find_unused_port()
1073+
1074+
messages = []
1075+
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
1076+
1077+
async def client():
1078+
rd, wr = await asyncio.open_connection('localhost', port)
1079+
wr.write(b'test msg')
1080+
await wr.drain()
1081+
wr.close()
1082+
await wr.wait_closed()
1083+
1084+
async def main():
1085+
async def handle_echo(reader, writer):
1086+
raise Exception('test')
1087+
1088+
server = await asyncio.start_server(
1089+
handle_echo, 'localhost', port)
1090+
await server.start_serving()
1091+
await client()
1092+
server.close()
1093+
await server.wait_closed()
1094+
1095+
self.loop.run_until_complete(main())
1096+
1097+
self.assertEqual(messages[0]['message'],
1098+
'Unhandled exception in client_connected_cb')
1099+
10711100

10721101
if __name__ == '__main__':
10731102
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Call loop exception handler for exceptions in ``client_connected_cb`` of :func:`asyncio.start_server` so that applications can handle it. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)