From e94f41b381c8eb1c3b7e64c09e95f519c78bd144 Mon Sep 17 00:00:00 2001 From: GochoMugo Date: Thu, 9 Feb 2017 20:09:31 +0300 Subject: [PATCH] src/polling: Emit 'error' instead --- doc/usage.md | 1 + src/telegramPolling.js | 20 +++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/doc/usage.md b/doc/usage.md index 3a17700f..987855be 100644 --- a/doc/usage.md +++ b/doc/usage.md @@ -36,6 +36,7 @@ that emits the following events: 1. `pre_checkout_query`: Received a new incoming pre-checkout query 1. `polling_error`: Error occurred during polling. See [polling errors](#polling-errors). 1. `webhook_error`: Error occurred handling a webhook request. See [webhook errors](#webhook-errors). +1. `error`: Unexpected error occurred, usually fatal! **Tip:** Its much better to listen a specific event rather than on `message` in order to stay safe from the content. diff --git a/src/telegramPolling.js b/src/telegramPolling.js index 8df5d1bb..711a62f9 100644 --- a/src/telegramPolling.js +++ b/src/telegramPolling.js @@ -1,3 +1,4 @@ +const errors = require('./errors'); const debug = require('debug')('node-telegram-bot-api'); const deprecate = require('depd')('node-telegram-bot-api'); const ANOTHER_WEB_HOOK_USED = 409; @@ -105,13 +106,24 @@ class TelegramBotPolling { updates.forEach(update => { this.options.params.offset = update.update_id + 1; debug('updated offset: %s', this.options.params.offset); - this.bot.processUpdate(update); + try { + this.bot.processUpdate(update); + } catch (err) { + err._processing = true; + throw err; + } }); return null; }) .catch(err => { debug('polling error: %s', err.message); + if (!err._processing) { + return this._error(err); + } + delete err._processing; /* + * An error occured while processing the items, + * i.e. in `this.bot.processUpdate()` above. * We need to mark the already-processed items * to avoid fetching them again once the application * is restarted, or moves to next polling interval @@ -135,15 +147,17 @@ class TelegramBotPolling { * We have to log this to stderr to ensure devops * understands that they may receive already-processed items * on app restart. + * We simply can not rescue this situation, emit "error" + * event, with the hope that the application exits. */ /* eslint-disable no-console */ const bugUrl = 'https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067'; console.error('error: Internal handling of The Offset Infinite Loop failed'); - console.error(`error: This was due to error '${requestErr}'`); + console.error(`error: Due to error '${requestErr}'`); console.error('error: You may receive already-processed updates on app restart'); console.error(`error: Please see ${bugUrl} for more information`); /* eslint-enable no-console */ - throw err; + return this.bot.emit('error', new errors.FatalError(err)); }); }) .finally(() => {