Skip to content

Commit ad21253

Browse files
Exireldgw
andcommitted
irc: properly manage exceptions in the run-forever loop
Co-authored-by: dgw <[email protected]>
1 parent c4a34f7 commit ad21253

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

sopel/irc/backends.py

Lines changed: 39 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,25 @@ 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+
517+
except Exception as err:
518+
LOGGER.error('Unexpected error on read: %s', err)
519+
self.log_exception()
520+
521+
# task done (connection closed without error)
505522
else:
506523
LOGGER.debug('Reader received EOF.')
507524

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

520556
def run_forever(self) -> None:

0 commit comments

Comments
 (0)