From e0863dcce94783283350be863f5fff226ec90de8 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Tue, 8 Sep 2015 16:00:26 +0500 Subject: [PATCH] pass errors in stream mode Closes #97 --- index.js | 8 ++++++++ test/test-stream.js | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/index.js b/index.js index c3aa329..28cae16 100644 --- a/index.js +++ b/index.js @@ -161,11 +161,19 @@ function asStream(opts) { ee.on('response', function (res) { proxy.setReadable(res); + + var statusCode = res.statusCode; + if (statusCode < 200 || statusCode > 299) { + proxy.emit('error', new got.HTTPError(statusCode, opts), null, res); + } + proxy.emit('response', res); }); ee.on('redirect', proxy.emit.bind(proxy, 'redirect')); + ee.on('error', proxy.emit.bind(proxy, 'error')); + return proxy; } diff --git a/test/test-stream.js b/test/test-stream.js index 6b11eef..b8cbef8 100644 --- a/test/test-stream.js +++ b/test/test-stream.js @@ -19,6 +19,11 @@ s.on('/redirect', function (req, res) { res.end(); }); +s.on('/error', function (req, res) { + res.statusCode = 404; + res.end(); +}); + test('setup', function (t) { s.listen(s.port, function () { t.end(); @@ -82,6 +87,22 @@ test('response event', function (t) { }); }); +test('error event', function (t) { + t.plan(4); + + got.stream(s.url + '/error') + .on('error', function (err, data, res) { + t.equal(err.message, 'Response code 404 (Not Found)'); + t.equal(null, data); + t.ok(res); + }); + + got.stream('.com') + .on('error', function (err) { + t.ok(/getaddrinfo ENOTFOUND/.test(err.message)); + }); +}); + test('cleanup', function (t) { s.close(); t.end();