Browse Source

Merge pull request #88 from floatdrop/new-errors

Explicit Error classes
http2
Vsevolod Strukchinsky 10 years ago
parent
commit
aba353f6fb
  1. 69
      index.js
  2. 2
      package.json
  3. 25
      readme.md
  4. 7
      test/test-arguments.js
  5. 10
      test/test-error.js
  6. 4
      test/test-gzip.js
  7. 1
      test/test-helpers.js
  8. 2
      test/test-http.js
  9. 12
      test/test-json.js
  10. 5
      test/test-redirects.js
  11. 1
      test/test-stream.js

69
index.js

@ -3,7 +3,6 @@ var EventEmitter = require('events').EventEmitter;
var http = require('http'); var http = require('http');
var https = require('https'); var https = require('https');
var urlLib = require('url'); var urlLib = require('url');
var util = require('util');
var querystring = require('querystring'); var querystring = require('querystring');
var objectAssign = require('object-assign'); var objectAssign = require('object-assign');
var duplexify = require('duplexify'); var duplexify = require('duplexify');
@ -13,17 +12,9 @@ var timedOut = require('timed-out');
var prependHttp = require('prepend-http'); var prependHttp = require('prepend-http');
var lowercaseKeys = require('lowercase-keys'); var lowercaseKeys = require('lowercase-keys');
var isRedirect = require('is-redirect'); var isRedirect = require('is-redirect');
var NestedErrorStacks = require('nested-error-stacks');
var pinkiePromise = require('pinkie-promise'); var pinkiePromise = require('pinkie-promise');
var unzipResponse = require('unzip-response'); var unzipResponse = require('unzip-response');
var createErrorClass = require('create-error-class');
function GotError(message, nested) {
NestedErrorStacks.call(this, message, nested);
objectAssign(this, nested, {nested: this.nested});
}
util.inherits(GotError, NestedErrorStacks);
GotError.prototype.name = 'GotError';
function requestAsEventEmitter(opts) { function requestAsEventEmitter(opts) {
opts = opts || {}; opts = opts || {};
@ -33,7 +24,6 @@ function requestAsEventEmitter(opts) {
var get = function (opts) { var get = function (opts) {
var fn = opts.protocol === 'https:' ? https : http; var fn = opts.protocol === 'https:' ? https : http;
var url = urlLib.format(opts);
var req = fn.request(opts, function (res) { var req = fn.request(opts, function (res) {
var statusCode = res.statusCode; var statusCode = res.statusCode;
@ -41,11 +31,11 @@ function requestAsEventEmitter(opts) {
res.resume(); res.resume();
if (++redirectCount > 10) { if (++redirectCount > 10) {
ee.emit('error', new GotError('Redirected 10 times. Aborting.'), undefined, res); ee.emit('error', new got.MaxRedirectsError(statusCode, opts), null, res);
return; return;
} }
var redirectUrl = urlLib.resolve(url, res.headers.location); var redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location);
var redirectOpts = objectAssign({}, opts, urlLib.parse(redirectUrl)); var redirectOpts = objectAssign({}, opts, urlLib.parse(redirectUrl));
ee.emit('redirect', res, redirectOpts); ee.emit('redirect', res, redirectOpts);
@ -56,7 +46,7 @@ function requestAsEventEmitter(opts) {
ee.emit('response', unzipResponse(res)); ee.emit('response', unzipResponse(res));
}).once('error', function (err) { }).once('error', function (err) {
ee.emit('error', new GotError('Request to ' + url + ' failed', err)); ee.emit('error', new got.RequestError(err, opts));
}); });
if (opts.timeout) { if (opts.timeout) {
@ -72,7 +62,6 @@ function requestAsEventEmitter(opts) {
function asCallback(opts, cb) { function asCallback(opts, cb) {
var ee = requestAsEventEmitter(opts); var ee = requestAsEventEmitter(opts);
var url = urlLib.format(opts);
ee.on('request', function (req) { ee.on('request', function (req) {
if (isStream.readable(opts.body)) { if (isStream.readable(opts.body)) {
@ -87,22 +76,21 @@ function asCallback(opts, cb) {
ee.on('response', function (res) { ee.on('response', function (res) {
readAllStream(res, opts.encoding, function (err, data) { readAllStream(res, opts.encoding, function (err, data) {
if (err) { if (err) {
cb(new GotError('Reading ' + url + ' response failed', err), null, res); cb(new got.ReadError(err, opts), null, res);
return; return;
} }
var statusCode = res.statusCode; var statusCode = res.statusCode;
if (statusCode < 200 || statusCode > 299) { if (statusCode < 200 || statusCode > 299) {
err = new GotError(opts.method + ' ' + url + ' response code is ' + statusCode + ' (' + http.STATUS_CODES[statusCode] + ')', err); err = new got.HTTPError(statusCode, opts);
err.code = statusCode;
} }
if (opts.json && statusCode !== 204) { if (opts.json && statusCode !== 204) {
try { try {
data = JSON.parse(data); data = JSON.parse(data);
} catch (e) { } catch (e) {
err = new GotError('Parsing ' + url + ' response failed', new GotError(e.message, err)); err = new got.ParseError(e, opts);
} }
} }
@ -133,7 +121,7 @@ function asStream(opts) {
var proxy = duplexify(); var proxy = duplexify();
if (opts.json) { if (opts.json) {
throw new GotError('got can not be used as stream when options.json is used'); throw new Error('got can not be used as stream when options.json is used');
} }
if (opts.body) { if (opts.body) {
@ -177,11 +165,11 @@ function asStream(opts) {
function normalizeArguments(url, opts) { function normalizeArguments(url, opts) {
if (typeof url !== 'string' && typeof url !== 'object') { if (typeof url !== 'string' && typeof url !== 'object') {
throw new GotError('Parameter `url` must be a string or object, not ' + typeof url); throw new Error('Parameter `url` must be a string or object, not ' + typeof url);
} }
opts = objectAssign( opts = objectAssign(
{protocol: 'http:'}, {protocol: 'http:', path: ''},
typeof url === 'string' ? urlLib.parse(prependHttp(url)) : url, typeof url === 'string' ? urlLib.parse(prependHttp(url)) : url,
opts opts
); );
@ -191,17 +179,13 @@ function normalizeArguments(url, opts) {
'accept-encoding': 'gzip,deflate' 'accept-encoding': 'gzip,deflate'
}, lowercaseKeys(opts.headers)); }, lowercaseKeys(opts.headers));
if (opts.pathname) {
opts.path = opts.pathname;
}
var query = opts.query; var query = opts.query;
if (query) { if (query) {
if (typeof query !== 'string') { if (typeof query !== 'string') {
opts.query = querystring.stringify(query); opts.query = querystring.stringify(query);
} }
opts.path = opts.pathname + '?' + opts.query; opts.path = opts.path.split('?')[0] + '?' + opts.query;
delete opts.query; delete opts.query;
} }
@ -212,7 +196,7 @@ function normalizeArguments(url, opts) {
var body = opts.body; var body = opts.body;
if (body) { if (body) {
if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream.readable(body)) { if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream.readable(body)) {
throw new GotError('options.body must be a ReadableStream, string or Buffer'); throw new Error('options.body must be a ReadableStream, string or Buffer');
} }
opts.method = opts.method || 'POST'; opts.method = opts.method || 'POST';
@ -274,4 +258,33 @@ helpers.forEach(function (el) {
}; };
}); });
function stdError(error, opts) {
objectAssign(this, {
message: error.message,
code: error.code,
host: opts.host,
hostname: opts.hostname,
method: opts.method,
path: opts.path
});
}
got.RequestError = createErrorClass('RequestError', stdError);
got.ReadError = createErrorClass('ReadError', stdError);
got.ParseError = createErrorClass('ParseError', stdError);
got.HTTPError = createErrorClass('HTTPError', function (statusCode, opts) {
stdError.call(this, {}, opts);
this.statusCode = statusCode;
this.statusMessage = http.STATUS_CODES[this.statusCode];
this.message = 'Response code ' + this.statusCode + ' (' + this.statusMessage + ')';
});
got.MaxRedirectsError = createErrorClass('MaxRedirectsError', function (statusCode, opts) {
stdError.call(this, {}, opts);
this.statusCode = statusCode;
this.statusMessage = http.STATUS_CODES[this.statusCode];
this.message = 'Redirected 10 times. Aborting.';
});
module.exports = got; module.exports = got;

2
package.json

@ -41,11 +41,11 @@
"fetch" "fetch"
], ],
"dependencies": { "dependencies": {
"create-error-class": "^2.0.0",
"duplexify": "^3.2.0", "duplexify": "^3.2.0",
"is-redirect": "^1.0.0", "is-redirect": "^1.0.0",
"is-stream": "^1.0.0", "is-stream": "^1.0.0",
"lowercase-keys": "^1.0.0", "lowercase-keys": "^1.0.0",
"nested-error-stacks": "^1.0.0",
"object-assign": "^3.0.0", "object-assign": "^3.0.0",
"pinkie-promise": "^1.0.0", "pinkie-promise": "^1.0.0",
"prepend-http": "^1.0.0", "prepend-http": "^1.0.0",

25
readme.md

@ -152,6 +152,29 @@ When in stream mode, you can listen for events:
Sets `options.method` to the method name and makes a request. Sets `options.method` to the method name and makes a request.
## Errors
Each Error contains (if available) `host`, `hostname`, `method` and `path` properties to make debug easier.
#### got.RequestError
Happens, when making request failed. Should contain `code` property with error class code (like `ECONNREFUSED`).
#### got.ReadError
Happens, when reading from response stream failed.
#### got.ParseError
Happens, when `json` option is enabled and `JSON.parse` failed.
#### got.HTTPError
Happens, when server response code is not 2xx. Contains `statusCode` and `statusMessage`.
#### got.MaxRedirectsError
Happens, when server redirects you more than 10 times.
## Proxy ## Proxy
@ -201,8 +224,6 @@ This should only ever be done if you have Node version 0.10.x and at the top-lev
## Related ## Related
- [gh-got](https://github.com/sindresorhus/gh-got) - Convenience wrapper for interacting with the GitHub API - [gh-got](https://github.com/sindresorhus/gh-got) - Convenience wrapper for interacting with the GitHub API
- [got-promise](https://github.com/floatdrop/got-promise) - Promise wrapper
## Created by ## Created by

7
test/test-arguments.js

@ -46,13 +46,6 @@ test('overrides querystring from opts', function (t) {
}); });
}); });
test('pathname confusion', function (t) {
got({protocol: 'http:', hostname: s.host, port: s.port, pathname: '/test'}, function (err) {
t.error(err);
t.end();
});
});
test('cleanup', function (t) { test('cleanup', function (t) {
s.close(); s.close();
t.end(); t.end();

10
test/test-error.js

@ -18,7 +18,9 @@ test('setup', function (t) {
test('error message', function (t) { test('error message', function (t) {
got(s.url, function (err) { got(s.url, function (err) {
t.ok(err); t.ok(err);
t.equal(err.message, 'GET http://localhost:6767/ response code is 404 (Not Found)'); t.equal(err.message, 'Response code 404 (Not Found)');
t.equal(err.host, 'localhost:6767');
t.equal(err.method, 'GET');
t.end(); t.end();
}); });
}); });
@ -26,9 +28,9 @@ test('error message', function (t) {
test('dns error message', function (t) { test('dns error message', function (t) {
got('.com', function (err) { got('.com', function (err) {
t.ok(err); t.ok(err);
t.equal(err.message, 'Request to http://.com/ failed'); t.ok(/getaddrinfo ENOTFOUND/.test(err.message));
t.ok(err.nested); t.equal(err.host, '.com');
t.ok(/getaddrinfo ENOTFOUND/.test(err.nested.message)); t.equal(err.method, 'GET');
t.end(); t.end();
}); });
}); });

4
test/test-gzip.js

@ -39,7 +39,9 @@ test('ungzip content', function (t) {
test('ungzip error', function (t) { test('ungzip error', function (t) {
got(s.url + '/corrupted', function (err) { got(s.url + '/corrupted', function (err) {
t.ok(err); t.ok(err);
t.equal(err.message, 'Reading ' + s.url + '/corrupted response failed'); t.equal(err.message, 'incorrect header check');
t.equal(err.path, '/corrupted');
t.equal(err.name, 'ReadError');
t.end(); t.end();
}); });
}); });

1
test/test-helpers.js

@ -37,7 +37,6 @@ test('promise mode', function (t) {
got.get(s.url + '/404') got.get(s.url + '/404')
.catch(function (err) { .catch(function (err) {
t.equal(err.message, 'GET http://localhost:6767/404 response code is 404 (Not Found)');
t.equal(err.response.body, 'not found'); t.equal(err.response.body, 'not found');
}); });
}); });

2
test/test-http.js

@ -56,7 +56,7 @@ test('empty response', function (t) {
test('error with code', function (t) { test('error with code', function (t) {
got(s.url + '/404', function (err, data) { got(s.url + '/404', function (err, data) {
t.ok(err); t.ok(err);
t.equal(err.code, 404); t.equal(err.statusCode, 404);
t.equal(data, 'not'); t.equal(data, 'not');
t.end(); t.end();
}); });

12
test/test-json.js

@ -51,9 +51,8 @@ test('json option should not parse responses without a body', function (t) {
test('json option wrap parsing errors', function (t) { test('json option wrap parsing errors', function (t) {
got(s.url + '/invalid', {json: true}, function (err) { got(s.url + '/invalid', {json: true}, function (err) {
t.ok(err); t.ok(err);
t.equal(err.message, 'Parsing ' + s.url + '/invalid response failed'); t.equal(err.message, 'Unexpected token /');
t.ok(err.nested); t.equal(err.path, '/invalid');
t.equal(err.nested.message, 'Unexpected token /');
t.end(); t.end();
}); });
}); });
@ -70,11 +69,8 @@ test('json option should catch errors on invalid non-200 responses', function (t
got(s.url + '/non200-invalid', {json: true}, function (err, json) { got(s.url + '/non200-invalid', {json: true}, function (err, json) {
t.ok(err); t.ok(err);
t.deepEqual(json, 'Internal error'); t.deepEqual(json, 'Internal error');
t.equal(err.message, 'Parsing http://localhost:6767/non200-invalid response failed'); t.equal(err.message, 'Unexpected token I');
t.ok(err.nested); t.equal(err.path, '/non200-invalid');
t.equal(err.nested.message, 'Unexpected token I');
t.ok(err.nested.nested);
t.equal(err.nested.nested.message, 'GET http://localhost:6767/non200-invalid response code is 500 (Internal Server Error)');
t.end(); t.end();
}); });
}); });

5
test/test-redirects.js

@ -84,8 +84,9 @@ test('hostname+path in options are not breaking redirects', function (t) {
test('redirect only GET and HEAD requests', function (t) { test('redirect only GET and HEAD requests', function (t) {
got(s.url + '/relative', {body: 'wow'}, function (err) { got(s.url + '/relative', {body: 'wow'}, function (err) {
t.equal(err.message, 'POST http://localhost:6767/relative response code is 302 (Moved Temporarily)'); t.equal(err.message, 'Response code 302 (Moved Temporarily)');
t.equal(err.code, 302); t.equal(err.path, '/relative');
t.equal(err.statusCode, 302);
t.end(); t.end();
}); });
}); });

1
test/test-stream.js

@ -1,7 +1,6 @@
'use strict'; 'use strict';
var test = require('tap').test; var test = require('tap').test;
var from2Array = require('from2-array');
var got = require('../'); var got = require('../');
var server = require('./server.js'); var server = require('./server.js');
var s = server.createServer(); var s = server.createServer();

Loading…
Cancel
Save