Skip to content

Commit

Permalink
Log Exceptions while building context and start on tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Bibo-Joshi committed Apr 25, 2024
1 parent ee88973 commit 79a319b
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 10 deletions.
41 changes: 32 additions & 9 deletions telegram/ext/_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,13 +1248,24 @@ async def process_update(self, update: object) -> None:
context = None
any_blocking = False # Flag which is set to True if any handler specifies block=True

for handlers in self.handlers.values():
for handlers in self.handlers.values(): # pylint: disable=too-many-nested-blocks
try:
for handler in handlers:
check = handler.check_update(update) # Should the handler handle this update?
if not (check is None or check is False): # if yes,
if not context: # build a context if not already built
context = self.context_types.context.from_update(update, self)
try:
context = self.context_types.context.from_update(update, self)
except Exception as exc:
_LOGGER.critical(
(
"Error while building CallbackContext for update %s. "
"Update will not be processed."
),
update,
exc_info=exc,
)
return
await context.refresh_data()
coroutine: Coroutine = handler.handle_update(update, self, check, context)

Expand Down Expand Up @@ -1809,13 +1820,25 @@ async def process_error(
callback,
block,
) in self.error_handlers.items():
context = self.context_types.context.from_error(
update=update,
error=error,
application=self,
job=job,
coroutine=coroutine,
)
try:
context = self.context_types.context.from_error(
update=update,
error=error,
application=self,
job=job,
coroutine=coroutine,
)
except Exception as exc:
_LOGGER.critical(

Check warning on line 1832 in telegram/ext/_application.py

View check run for this annotation

Codecov / codecov/patch

telegram/ext/_application.py#L1831-L1832

Added lines #L1831 - L1832 were not covered by tests
(
"Error while building CallbackContext for exception %s. "
"Exception will not be processed by error handlers."
),
error,
exc_info=exc,
)
return False

Check warning on line 1840 in telegram/ext/_application.py

View check run for this annotation

Codecov / codecov/patch

telegram/ext/_application.py#L1840

Added line #L1840 was not covered by tests

if not block or ( # If error handler has `block=False`, create a Task to run cb
block is DEFAULT_TRUE
and isinstance(self.bot, ExtBot)
Expand Down
13 changes: 12 additions & 1 deletion telegram/ext/_jobqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
except ImportError:
APS_AVAILABLE = False

from telegram._utils.logging import get_logger
from telegram._utils.repr import build_repr_with_selected_attrs
from telegram._utils.types import JSONDict
from telegram.ext._extbot import ExtBot
Expand All @@ -44,6 +45,7 @@


_ALL_DAYS = tuple(range(7))
_LOGGER = get_logger(__name__)


class JobQueue(Generic[CCT]):
Expand Down Expand Up @@ -953,7 +955,16 @@ async def _run(
self, application: "Application[Any, CCT, Any, Any, Any, JobQueue[CCT]]"
) -> None:
try:
context = application.context_types.context.from_job(self, application)
try:
context = application.context_types.context.from_job(self, application)
except Exception as exc:
_LOGGER.critical(

Check warning on line 961 in telegram/ext/_jobqueue.py

View check run for this annotation

Codecov / codecov/patch

telegram/ext/_jobqueue.py#L960-L961

Added lines #L960 - L961 were not covered by tests
"Error while building CallbackContext for job %s. Job will not be run.",
self._job,
exc_info=exc,
)
return

await context.refresh_data()
await self.callback(context)
except Exception as exc:
Expand Down
39 changes: 39 additions & 0 deletions tests/ext/test_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -2421,3 +2421,42 @@ async def callback(update, context):
assert len(assertions) == 5
for key, value in assertions.items():
assert value, f"assertion '{key}' failed!"

async def test_process_update_exception_in_building_context(self, monkeypatch, caplog, app):
# Makes sure that exceptions in building the context don't stop the application
exception = ValueError("TestException")
original_from_update = CallbackContext.from_update

def raise_exception(update, application):
if update == 1:
raise exception
return original_from_update(update, application)

monkeypatch.setattr(CallbackContext, "from_update", raise_exception)

received_updates = set()

async def callback(update, context):
received_updates.add(update)

app.add_handler(TypeHandler(int, callback))

async with app:
with caplog.at_level(logging.CRITICAL):
await app.process_update(1)

assert received_updates == set()
assert len(caplog.records) == 1
record = caplog.records[0]
assert record.name == "telegram.ext.Application"
assert record.getMessage().startswith(
"Error while building CallbackContext for update 1"
)
assert record.levelno == logging.CRITICAL

caplog.clear()
with caplog.at_level(logging.CRITICAL):
await app.process_update(2)

assert received_updates == {2}
assert len(caplog.records) == 0

0 comments on commit 79a319b

Please sign in to comment.