Skip to content

Commit

Permalink
Print unhandled errors to stderr if logging is not configured
Browse files Browse the repository at this point in the history
This should mitigate "the code doesn't work but there are no errors"
situations. Users not wanting this behaviour can configure logging
with a high-enough level that won't print anything, or set a filter.
  • Loading branch information
Lonami committed Jan 30, 2021
1 parent 4cc9645 commit b88ec4b
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions telethon/client/updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
import inspect
import itertools
import random
import sys
import time
import traceback
import typing
import logging

from .. import events, utils, errors
from ..events.common import EventBuilder, EventCommon
Expand Down Expand Up @@ -281,6 +284,16 @@ async def catch_up(self: 'TelegramClient'):

# region Private methods

def _log_exc(self: 'TelegramClient', msg, *args):
"""
Log an exception, using `stderr` if `logging` is not configured.
"""
if logging.root.hasHandlers():
self._log[__name__].exception(msg, *args)
else:
print('[ERROR/telethon]:', msg % args, file=sys.stderr)
traceback.print_exc()

# It is important to not make _handle_update async because we rely on
# the order that the updates arrive in to update the pts and date to
# be always-increasing. There is also no need to make this async.
Expand Down Expand Up @@ -464,8 +477,7 @@ async def _dispatch_update(self: 'TelegramClient', update, others, channel_id, p
except Exception as e:
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].exception('Unhandled exception on %s',
name)
self._log_exc('Unhandled exception on %s', name)

async def _dispatch_event(self: 'TelegramClient', event):
"""
Expand Down Expand Up @@ -506,8 +518,7 @@ async def _dispatch_event(self: 'TelegramClient', event):
except Exception as e:
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].exception('Unhandled exception on %s',
name)
self._log_exc('Unhandled exception on %s', name)

async def _get_difference(self: 'TelegramClient', update, channel_id, pts_date):
"""
Expand Down Expand Up @@ -610,8 +621,7 @@ async def _handle_auto_reconnect(self: 'TelegramClient'):
self._log[__name__].warning('Failed to get missed updates after '
'reconnect: %r', e)
except Exception:
self._log[__name__].exception('Unhandled exception while getting '
'update difference after reconnect')
self._log_exc('Unhandled exception while getting update difference after reconnect')

# endregion

Expand Down

0 comments on commit b88ec4b

Please sign in to comment.