Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] errors: add internal/errors module #6573

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/_debugger.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ Protocol.prototype.execute = function(d) {
break;

default:
throw new Error('Unknown state');
const errors = require('internal/errors');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't requires be at the top of the file?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When there are only one or two cases in a file, I did it like this so the
require is only called in error conditions
On May 9, 2016 5:27 PM, "Rod Vagg" notifications@github.com wrote:

In lib/_debugger.js
#6573 (comment):

@@ -126,7 +126,8 @@ Protocol.prototype.execute = function(d) {
break;

 default:
  •  throw new Error('Unknown state');
    
  •  const errors = require('internal/errors');
    

shouldn't requires be at the top of the file?


You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/nodejs/node/pull/6573/files/56d34d36a841cee62adb657548b90bd27ebce870#r62595987

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lazy loading is pretty common in core code. Though I'm not sure how much it actually saves us now.

throw new errors.Error('UNKNOWNSTATE');
}
};

Expand Down
16 changes: 8 additions & 8 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const errors = require('internal/errors');
const util = require('util');
const net = require('net');
const url = require('url');
Expand All @@ -22,7 +23,7 @@ function ClientRequest(options, cb) {
if (typeof options === 'string') {
options = url.parse(options);
if (!options.hostname) {
throw new Error('Unable to determine the domain name');
throw new errors.Error('DNSUNKNOWNDOMAIN');
}
} else {
options = util._extend({}, options);
Expand Down Expand Up @@ -50,10 +51,11 @@ function ClientRequest(options, cb) {
// well, and b) possibly too restrictive for real-world usage. That's
// why it only scans for spaces because those are guaranteed to create
// an invalid request.
throw new TypeError('Request path contains unescaped characters');
throw new errors.TypeError('HTTPINVALIDPATH');
} else if (protocol !== expectedProtocol) {
throw new Error('Protocol "' + protocol + '" not supported. ' +
'Expected "' + expectedProtocol + '"');
throw new errors.Error('HTTPUNSUPPORTEDPROTOCOL',
protocol,
expectedProtocol);
}

const defaultPort = options.defaultPort ||
Expand All @@ -70,7 +72,7 @@ function ClientRequest(options, cb) {

var method = self.method = (options.method || 'GET').toUpperCase();
if (!common._checkIsHttpToken(method)) {
throw new TypeError('Method must be a valid HTTP token');
throw new errors.TypeError('HTTPMETHODINVALID');
}
self.path = options.path || '/';
if (cb) {
Expand Down Expand Up @@ -247,9 +249,7 @@ function emitAbortNT(self) {


function createHangUpError() {
var error = new Error('socket hang up');
error.code = 'ECONNRESET';
return error;
return new errors.Error('ECONNRESET');
}


Expand Down
31 changes: 14 additions & 17 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const errors = require('internal/errors');
const assert = require('assert').ok;
const Stream = require('stream');
const timers = require('timers');
Expand Down Expand Up @@ -302,11 +303,10 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {

function storeHeader(self, state, field, value) {
if (!common._checkIsHttpToken(field)) {
throw new TypeError(
'Header name must be a valid HTTP Token ["' + field + '"]');
throw new errors.TypeError('HTTPINVALIDTOKEN', field);
}
if (common._checkInvalidHeaderChar(value) === true) {
throw new TypeError('The header content contains invalid characters');
throw new errors.TypeError('HTTPINVALIDHEADER');
}
state.messageHeader += field + ': ' + escapeHeaderValue(value) + CRLF;

Expand Down Expand Up @@ -336,17 +336,15 @@ function storeHeader(self, state, field, value) {

OutgoingMessage.prototype.setHeader = function(name, value) {
if (!common._checkIsHttpToken(name))
throw new TypeError(
'Header name must be a valid HTTP Token ["' + name + '"]');
throw new errors.TypeError('HTTPINVALIDTOKEN', name);
if (typeof name !== 'string')
throw new TypeError('"name" should be a string in setHeader(name, value)');
throw new errors.TypeError('INVALIDARG', 'name', 'string');
if (value === undefined)
throw new Error('"value" required in setHeader("' + name + '", value)');
throw new errors.Error('REQUIREDARG', 'value');
if (this._header)
throw new Error('Can\'t set headers after they are sent.');
if (common._checkInvalidHeaderChar(value) === true) {
throw new TypeError('The header content contains invalid characters');
}
throw new errors.Error('HEADERSSENT');
if (common._checkInvalidHeaderChar(value) === true)
throw new errors.TypeError('HTTPINVALIDHEADER');
if (this._headers === null)
this._headers = {};

Expand All @@ -361,7 +359,7 @@ OutgoingMessage.prototype.setHeader = function(name, value) {

OutgoingMessage.prototype.getHeader = function(name) {
if (arguments.length < 1) {
throw new Error('"name" argument is required for getHeader(name)');
throw new errors.Error('REQUIREDARG', 'name');
}

if (!this._headers) return;
Expand Down Expand Up @@ -440,7 +438,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
}

if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
throw new TypeError('First argument must be a string or Buffer');
throw new errors.TypeError('INVALIDARG', 'chunk', ['Buffer', 'string']);
}


Expand Down Expand Up @@ -515,11 +513,10 @@ OutgoingMessage.prototype.addTrailers = function(headers) {
value = headers[key];
}
if (!common._checkIsHttpToken(field)) {
throw new TypeError(
'Trailer name must be a valid HTTP Token ["' + field + '"]');
throw new errors.TypeError('HTTPINVALIDTOKEN', field);
}
if (common._checkInvalidHeaderChar(value) === true) {
throw new TypeError('The trailer content contains invalid characters');
throw new errors.TypeError('HTTPINVALIDTRAILER');
}
this._trailer += field + ': ' + escapeHeaderValue(value) + CRLF;
}
Expand All @@ -539,7 +536,7 @@ OutgoingMessage.prototype.end = function(data, encoding, callback) {
}

if (data && typeof data !== 'string' && !(data instanceof Buffer)) {
throw new TypeError('First argument must be a string or Buffer');
throw new errors.TypeError('INVALIDARG', 'data', ['Buffer', 'string']);
}

if (this.finished) {
Expand Down
6 changes: 4 additions & 2 deletions lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,10 @@ ServerResponse.prototype.writeHead = function(statusCode, reason, obj) {
}

statusCode |= 0;
if (statusCode < 100 || statusCode > 999)
throw new RangeError(`Invalid status code: ${statusCode}`);
if (statusCode < 100 || statusCode > 999) {
const errors = require('internal/errors');
throw new errors.RangeError('HTTPINVALIDSTATUS', statusCode);
}

var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' +
this.statusMessage + CRLF;
Expand Down
21 changes: 20 additions & 1 deletion lib/_stream_readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,25 @@ var StringDecoder;

util.inherits(Readable, Stream);

// This does not use the internal/errors so that it can remain
// portable with the readable-streams module.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably also point to these from the main functions in case someone tries to edit them without knowing these exist?

function typeError(code, args) {
const assert = require('assert');
var msg;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why use var ? I think better to use let.

switch (code) {
case 'EINVALIDCHUNK':
msg = 'Invalid non-string/buffer chunk';
break;
default:
assert.fail(null, null, 'Unknown error code.');
}
var error = new TypeError(msg);
Error.captureStackTrace(error, typeError);
error.code = error.errno = code;
error.name = 'TypeError[' + code + ']';
return error;
}

const hasPrependListener = typeof EE.prototype.prependListener === 'function';

function prependListener(emitter, event, fn) {
Expand Down Expand Up @@ -396,7 +415,7 @@ function chunkInvalid(state, chunk) {
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
er = new typeError('EINVALIDCHUNK');
}
return er;
}
Expand Down
32 changes: 29 additions & 3 deletions lib/_stream_writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@ util.inherits(Writable, Stream);

function nop() {}

// This does not use the internal/errors so that it can remain
// portable with the readable-streams module.
function typeError(code, args) {
const assert = require('assert');
var msg;
switch (code) {
case 'EWRITENULL':
msg = 'May not write null values to stream.';
break;
case 'EINVALIDCHUNK':
msg = 'Invalid non-string/buffer chunk';
break;
case 'UNKNOWNENCODING':
assert(args && args[0]);
msg = 'Unknown encoding: ' + args[0];
break;
default:
assert.fail(null, null, 'Unknown error code.');
}
var error = new TypeError(msg);
Error.captureStackTrace(error, typeError);
error.code = error.errno = code;
error.name = 'TypeError[' + code + ']';
return error;
}

function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
Expand Down Expand Up @@ -181,12 +207,12 @@ function validChunk(stream, state, chunk, cb) {
// if we are not in object mode then throw
// if it is not a buffer, string, or undefined.
if (chunk === null) {
er = new TypeError('May not write null values to stream');
er = new typeError('EWRITENULL');
} else if (!(chunk instanceof Buffer) &&
typeof chunk !== 'string' &&
chunk !== undefined &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
er = new typeError('EINVALIDCHUNK');
}
if (er) {
stream.emit('error', er);
Expand Down Expand Up @@ -249,7 +275,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
if (typeof encoding === 'string')
encoding = encoding.toLowerCase();
if (!Buffer.isEncoding(encoding))
throw new TypeError('Unknown encoding: ' + encoding);
throw new typeError('UNKNOWNENCODING', [encoding]);
this._writableState.defaultEncoding = encoding;
return this;
};
Expand Down
3 changes: 2 additions & 1 deletion lib/_tls_wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,8 @@ function Server(/* [options], listener */) {
var timeout = options.handshakeTimeout || (120 * 1000);

if (typeof timeout !== 'number') {
throw new TypeError('handshakeTimeout must be a number');
const errors = require('internal/errors');
throw new errors.TypeError('INVALIDOPT', 'handshakeTimeout', 'number');
}

if (self.sessionTimeout) {
Expand Down
3 changes: 2 additions & 1 deletion lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,8 @@ function _throws(shouldThrow, block, expected, message) {
var actual;

if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
const errors = require('internal/errors');
throw new errors.TypeError('INVALIDARG', 'block', 'function');
}

if (typeof expected === 'string') {
Expand Down
Loading