Log Received Data on Deserialization Errors (#4304)

This commit is contained in:
Bibo-Joshi 2024-07-06 16:09:04 +02:00 committed by GitHub
parent 42d7c8c477
commit 98bed6f01a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 36 additions and 2 deletions

View file

@ -4374,7 +4374,16 @@ class Bot(TelegramObject, AsyncContextManager["Bot"]):
else:
self._LOGGER.debug("No new updates found.")
return Update.de_list(result, self)
try:
return Update.de_list(result, self)
except Exception as exc:
# This logging is in place mostly b/c we can't access the raw json data in Updater,
# where the exception is caught and logged again. Still, it might also be beneficial
# for custom usages of `get_updates`.
self._LOGGER.critical(
"Error while parsing updates! Received data was %r", result, exc_info=exc
)
raise exc
async def set_webhook(
self,

View file

@ -168,7 +168,8 @@ class TelegramHandler(tornado.web.RequestHandler):
except Exception as exc:
_LOGGER.critical(
"Something went wrong processing the data received from Telegram. "
"Received data was *not* processed!",
"Received data was *not* processed! Received data was: %r",
data,
exc_info=exc,
)
raise tornado.web.HTTPError(

View file

@ -1179,6 +1179,7 @@ class TestUpdater:
assert len(caplog.records) == 1
assert caplog.records[-1].getMessage().startswith("Something went wrong processing")
assert "Received data was: {" in caplog.records[-1].getMessage()
assert caplog.records[-1].name == "telegram.ext.Updater"
assert response.status_code == 400
assert response.text == self.response_text.format(

View file

@ -535,6 +535,29 @@ class TestBotWithoutRequest:
123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5}
)
async def test_get_updates_deserialization_error(self, bot, monkeypatch, caplog):
async def faulty_do_request(*args, **kwargs):
return (
HTTPStatus.OK,
b'{"ok": true, "result": [{"update_id": "1", "message": "unknown_format"}]}',
)
monkeypatch.setattr(HTTPXRequest, "do_request", faulty_do_request)
bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=bot.token)
with caplog.at_level(logging.CRITICAL), pytest.raises(AttributeError):
await bot.get_updates()
assert len(caplog.records) == 1
assert caplog.records[0].name == "telegram.ext.ExtBot"
assert caplog.records[0].levelno == logging.CRITICAL
assert caplog.records[0].getMessage() == (
"Error while parsing updates! Received data was "
"[{'update_id': '1', 'message': 'unknown_format'}]"
)
assert caplog.records[0].exc_info[0] is AttributeError
async def test_answer_web_app_query(self, bot, raw_bot, monkeypatch):
params = False