Skip to content

Commit c1e0cc7

Browse files
committed
irc: properly manage exceptions of the run-forever loop
1 parent 1116918 commit c1e0cc7

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

sopel/irc/backends.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,9 @@ async def read_forever(self) -> None:
313313
while not self._reader.at_eof():
314314
try:
315315
line: bytes = await self._reader.readuntil(separator=b'\r\n')
316-
except asyncio.exceptions.IncompleteReadError as e:
316+
except asyncio.exceptions.IncompleteReadError as err:
317317
LOGGER.warning('Receiving partial message from IRC.')
318-
line = e.partial
318+
line = err.partial
319319
except asyncio.exceptions.LimitOverrunError:
320320
LOGGER.exception('Unable to read from IRC server.')
321321
break
@@ -500,8 +500,24 @@ async def _run_forever(self) -> None:
500500
self._read_task = asyncio.create_task(self.read_forever())
501501
try:
502502
await self._read_task
503+
504+
# task was cancelled, i.e. another exception is responsible for that
503505
except asyncio.CancelledError:
504506
LOGGER.debug('Read task was cancelled.')
507+
508+
# connection reset requires a log, but no exception log
509+
except ConnectionResetError as err:
510+
LOGGER.error('Connection reset on read: %s', err)
511+
512+
# generic (connection) error requires a specific exception log
513+
except ConnectionError as err:
514+
LOGGER.error('Connection error on read: %s', err)
515+
self.log_exception()
516+
except Exception as err:
517+
LOGGER.error('Unexpected error on read: %s', err)
518+
self.log_exception()
519+
520+
# task done (connection closed without error)
505521
else:
506522
LOGGER.debug('Reader received EOF.')
507523

@@ -514,7 +530,25 @@ async def _run_forever(self) -> None:
514530
# nothing to read anymore
515531
LOGGER.debug('Shutting down writer.')
516532
self._writer.close()
517-
await self._writer.wait_closed()
533+
try:
534+
await self._writer.wait_closed()
535+
536+
# task was cancelled, i.e. another exception is responsible for that
537+
except asyncio.CancelledError:
538+
LOGGER.debug('Writer task was cancelled.')
539+
540+
# connection reset happened before on the read task
541+
except ConnectionResetError as err:
542+
LOGGER.debug('Connection reset while closing: %s', err)
543+
544+
# generic (connection) error requires a specific exception log
545+
except ConnectionError as err:
546+
LOGGER.error('Connection error while closing: %s', err)
547+
self.log_exception()
548+
except Exception:
549+
LOGGER.error('Unexpected error while shutting down socket.')
550+
self.log_exception()
551+
518552
LOGGER.debug('All clear, exiting now.')
519553

520554
def run_forever(self) -> None:

0 commit comments

Comments
 (0)