From 56ce51728083392132505218c05edd5cf9f60c58 Mon Sep 17 00:00:00 2001 From: Cr <631807682@qq.com> Date: Tue, 7 Jan 2020 17:19:31 +0800 Subject: [PATCH] fix: throw timeout error in promise interface when timedout (#1510) * fix: return timeout error in promise interface * test: timeout in promise interface --- src/request-base.js | 7 +++++++ test/timeout.js | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/request-base.js b/src/request-base.js index 357ae269f..5ccca0c9c 100644 --- a/src/request-base.js +++ b/src/request-base.js @@ -223,6 +223,7 @@ RequestBase.prototype._retry = function() { this._aborted = false; this.timedout = false; + this.timedoutError = null; return this._end(); }; @@ -246,6 +247,11 @@ RequestBase.prototype.then = function(resolve, reject) { this._fullfilledPromise = new Promise((resolve, reject) => { self.on('abort', () => { + if (this.timedout && this.timedoutError) { + reject(this.timedoutError); + return; + } + const err = new Error('Aborted'); err.code = 'ABORTED'; err.status = this.status; @@ -714,6 +720,7 @@ RequestBase.prototype._timeoutError = function(reason, timeout, errno) { err.code = 'ECONNABORTED'; err.errno = errno; this.timedout = true; + this.timedoutError = err; this.abort(); this.callback(err); }; diff --git a/test/timeout.js b/test/timeout.js index d10eb1690..387090738 100644 --- a/test/timeout.js +++ b/test/timeout.js @@ -24,6 +24,22 @@ describe('.timeout(ms)', function() { }); }); + it('should error in promise interface ', done => { + request + .get(`${base}/delay/500`) + .timeout(150) + .catch(err => { + assert(err, 'expected an error'); + assert.equal( + 'number', + typeof err.timeout, + 'expected an error with .timeout' + ); + assert.equal('ECONNABORTED', err.code, 'expected abort error code'); + done(); + }); + }); + it('should handle gzip timeout', done => { request .get(`${base}/delay/zip`)