fix: skip updates that do not fit their model instead of crashing - #45
Merged
Merged
Conversation
BushlanovDev#17 made unsupported update types silent: createUpdate() throws a LogicException, and createUpdateList() and WebhookHandler log it and skip the update. An update of a known type whose payload no longer fits the model (the API made a field optional, added an enum value) fails earlier, with a TypeError or ValueError from the model constructor, and nothing catches those: - createUpdateList() lets it out of getUpdates(), and LongPollingHandler::handle() catches only \Exception, so the loop stops and restarts into the same batch - WebhookHandler answers 500 and MAX keeps retrying createUpdate() now turns TypeError and ValueError into a LogicException (the original one kept as previous) and logs a warning with the payload, so the existing silent mode skips such an update. Errors thrown by user handlers are not affected.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Продолжение #17: тихий режим для неподдерживаемых типов событий из issue #15.
Проблема
#17 глушит
LogicExceptionизcreateUpdate():createUpdateList()иWebhookHandlerпишут debug и пропускают событие. Но бывает, что тип события известен, а данные не подходят модели: API сделал поле необязательным или добавил новое значение enum. Тогда ошибка возникает раньше —TypeErrorилиValueErrorв конструкторе модели, — и её никто не ловит:getUpdates(), аLongPollingHandler::handle()ловит только\Exception. Цикл останавливается, после перезапуска получает тот же пакет и падает снова.WebhookHandlerотвечает 500, и MAX повторяет запрос.Реальный пример: в схеме 0.0.33
User.last_activity_timeстал необязательным, и событие с таким пользователем падает сTypeError: Argument #6 ($lastActivityTime) must be of type int, null given. Так же сломает бота любое новое значениеChatAdminPermissionилиChatType:::from()броситValueError.Решение
createUpdate()превращаетTypeErrorиValueErrorвLogicException(исходная ошибка сохраняется вprevious) и пишетwarningс payload. Дальше работает существующий тихий режим: событие пропускается, бот продолжает работать. Расхождение с API видно в логе на уровне warning, а не debug.Ошибки в обработчиках пользователя не затронуты: преобразование происходит только внутри
createUpdate().Тесты
createUpdate()на payload без обязательного поля выбрасываетLogicExceptionсTypeErrorвpreviousи пишет warning.createUpdateList()пропускает событие сTypeErrorи событие с неизвестнымchat_type(ValueError), остальные события возвращает.WebhookHandlerс настоящейModelFactoryне падает и не вызывает обработчик.Покрытие осталось 100%. PR не зависит от #43 и от PR со сверкой схемы 0.0.33; вместе с ним новые модели оттуда тоже не уронят бота, если реальный API разойдётся со схемой.