Skip to content

Commit 1f5311b

Browse files
jh0kerEldinnie
authored andcommitted
catch exceptions in error handlerfor errors that happen during polling (2) (python-telegram-bot#810)
* catch exceptions in error handlerfor errors that happen during polling * add tests for error handlers that raise exceptions
1 parent eae139d commit 1f5311b

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

telegram/ext/dispatcher.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,12 @@ def process_update(self, update):
258258
"""
259259
# An error happened while polling
260260
if isinstance(update, TelegramError):
261-
self.dispatch_error(None, update)
261+
try:
262+
self.dispatch_error(None, update)
263+
except Exception:
264+
self.logger.exception('An uncaught error was raised while handling the error')
262265
return
266+
263267
for group in self.groups:
264268
try:
265269
for handler in (x for x in self.handlers[group] if x.check_update(update)):

tests/test_dispatcher.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ def reset(self):
4747
def error_handler(self, bot, update, error):
4848
self.received = error.message
4949

50+
def error_handler_raise_error(self, bot, update, error):
51+
raise Exception('Failing bigly')
52+
5053
def callback_increase_count(self, bot, update):
5154
self.count += 1
5255

@@ -78,6 +81,30 @@ def test_error_handler(self, dp):
7881
sleep(.1)
7982
assert self.received is None
8083

84+
def test_error_handler_that_raises_errors(self, dp):
85+
"""
86+
Make sure that errors raised in error handlers don't break the main loop of the dispatcher
87+
"""
88+
handler_raise_error = MessageHandler(Filters.all, self.callback_raise_error)
89+
handler_increase_count = MessageHandler(Filters.all, self.callback_increase_count)
90+
error = TelegramError('Unauthorized.')
91+
92+
dp.add_error_handler(self.error_handler_raise_error)
93+
94+
# From errors caused by handlers
95+
dp.add_handler(handler_raise_error)
96+
dp.update_queue.put(self.message_update)
97+
sleep(.1)
98+
99+
# From errors in the update_queue
100+
dp.remove_handler(handler_raise_error)
101+
dp.add_handler(handler_increase_count)
102+
dp.update_queue.put(error)
103+
dp.update_queue.put(self.message_update)
104+
sleep(.1)
105+
106+
assert self.count == 1
107+
81108
def test_run_async_multiple(self, bot, dp, dp2):
82109
def get_dispatcher_name(q):
83110
q.put(current_thread().name)

0 commit comments

Comments
 (0)