From b1d4e6b41654ad91185229e863f9e8260b5c2336 Mon Sep 17 00:00:00 2001 From: Yago Date: Fri, 1 Jan 2016 21:47:12 +0100 Subject: [PATCH] Handle request timeout. Catch errors while parsing JSON --- src/telegramPolling.js | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/telegramPolling.js b/src/telegramPolling.js index dc7a100..75ee46c 100644 --- a/src/telegramPolling.js +++ b/src/telegramPolling.js @@ -65,17 +65,25 @@ TelegramBotPolling.prototype._getUpdates = function () { }) }; debug('polling with options: %j', opts); - return requestPromise(opts).cancellable().then(function (resp) { - if (resp[0].statusCode !== 200) { - throw new Error(resp[0].statusCode+' '+resp[0].body); - } - var data = JSON.parse(resp[0].body); - if (data.ok) { - return data.result; - } else { - throw new Error(data.error_code+' '+data.description); - } - }); + return requestPromise(opts) + .cancellable() + .timeout((10 + this.timeout) * 1000) + .then(function (resp) { + if (resp[0].statusCode !== 200) { + throw new Error(resp[0].statusCode+' '+resp[0].body); + } + var data; + try { + data = JSON.parse(resp[0].body); + } catch (err) { + throw new Error('Error parsing Telegram response: %s', resp[0].body); + } + if (data.ok) { + return data.result; + } else { + throw new Error(data.error_code+' '+data.description); + } + }); }; module.exports = TelegramBotPolling;