diff --git a/index.js b/index.js index d4b4b779f..73246a78a 100644 --- a/index.js +++ b/index.js @@ -29,36 +29,41 @@ function requestAsEventEmitter(opts) { const get = opts => { const fn = opts.protocol === 'https:' ? https : http; + let req; - const req = fn.request(opts, res => { - const statusCode = res.statusCode; + try { + req = fn.request(opts, res => { + const statusCode = res.statusCode; - if (redirectUrl) { - res.url = redirectUrl; - } + if (redirectUrl) { + res.url = redirectUrl; + } - if (isRedirect(statusCode) && opts.followRedirect && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) { - res.resume(); + if (isRedirect(statusCode) && opts.followRedirect && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) { + res.resume(); - if (++redirectCount > 10) { - ee.emit('error', new got.MaxRedirectsError(statusCode, opts), null, res); - return; - } + if (++redirectCount > 10) { + ee.emit('error', new got.MaxRedirectsError(statusCode, opts), null, res); + return; + } - redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location); - const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl)); + redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location); + const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl)); - ee.emit('redirect', res, redirectOpts); + ee.emit('redirect', res, redirectOpts); - get(redirectOpts); + get(redirectOpts); - return; - } + return; + } - setImmediate(() => { - ee.emit('response', typeof unzipResponse === 'function' && req.method !== 'HEAD' ? unzipResponse(res) : res); + setImmediate(() => { + ee.emit('response', typeof unzipResponse === 'function' && req.method !== 'HEAD' ? unzipResponse(res) : res); + }); }); - }); + } catch (err) { + return ee.emit('error', new got.RequestError(err, opts)); + } req.once('error', err => { const backoff = opts.retries(++retryCount, err); diff --git a/test/error.js b/test/error.js index c8ad3850d..780178379 100644 --- a/test/error.js +++ b/test/error.js @@ -51,6 +51,15 @@ test('options.body error message', async t => { } }); +test('invalid url', async t => { + try { + await got('htttp://google.com'); + t.fail('Exception was not thrown'); + } catch (err) { + t.regex(err.message, /Protocol .+ not supported/); + } +}); + test.after('cleanup', async () => { await s.close(); });