errors,buffer: port errors to internal/errors

PR-URL: https://github.com/nodejs/node/pull/13976
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
This commit is contained in:
starkwang 2017-06-28 23:58:39 -04:00 committed by Refael Ackermann
parent 1562fb9ea7
commit dbfe8c4ea2
No known key found for this signature in database
GPG key ID: CD704BD80FDDDB64
28 changed files with 342 additions and 143 deletions

View file

@ -575,6 +575,11 @@ Used as special type of error that can be triggered whenever Node.js detects an
exceptional logic violation that should never occur. These are raised typically exceptional logic violation that should never occur. These are raised typically
by the `assert` module. by the `assert` module.
<a id="ERR_BUFFER_OUT_OF_BOUNDS"></a>
### ERR_BUFFER_OUT_OF_BOUNDS
Used when attempting to perform an operation outside the bounds of a `Buffer`.
<a id="ERR_CONSOLE_WRITABLE_STREAM"></a> <a id="ERR_CONSOLE_WRITABLE_STREAM"></a>
### ERR_CONSOLE_WRITABLE_STREAM ### ERR_CONSOLE_WRITABLE_STREAM
@ -625,6 +630,11 @@ to a Node.js API.
Used when an Array is not of the expected length or in a valid range. Used when an Array is not of the expected length or in a valid range.
<a id="ERR_INVALID_BUFFER_SIZE"></a>
### ERR_INVALID_BUFFER_SIZE
Used when performing a swap on a `Buffer` but it's size is not compatible with the operation.
<a id="ERR_INVALID_CALLBACK"></a> <a id="ERR_INVALID_CALLBACK"></a>
### ERR_INVALID_CALLBACK ### ERR_INVALID_CALLBACK
@ -781,6 +791,13 @@ would be possible by calling a callback more then once.
Used when an attempt is made to use crypto features while Node.js is not Used when an attempt is made to use crypto features while Node.js is not
compiled with OpenSSL crypto support. compiled with OpenSSL crypto support.
<a id="ERR_NO_LONGER_SUPPORTED"></a>
### ERR_NO_LONGER_SUPPORTED
Used when a Node.js API is called in an unsupported manner.
For example: `Buffer.write(string, encoding, offset[, length])`
<a id="ERR_PARSE_HISTORY_DATA"></a> <a id="ERR_PARSE_HISTORY_DATA"></a>
### ERR_PARSE_HISTORY_DATA ### ERR_PARSE_HISTORY_DATA
@ -844,6 +861,11 @@ Used to identify a specific kind of internal Node.js error that should not
typically be triggered by user code. Instances of this error point to an typically be triggered by user code. Instances of this error point to an
internal bug within the Node.js binary itself. internal bug within the Node.js binary itself.
<a id="ERR_UNKNOWN_ENCODING"></a>
### ERR_UNKNOWN_ENCODING
Used when an invalid or unknown encoding option is passed to an API.
<a id="ERR_UNKNOWN_SIGNAL"></a> <a id="ERR_UNKNOWN_SIGNAL"></a>
### ERR_UNKNOWN_SIGNAL ### ERR_UNKNOWN_SIGNAL

View file

@ -67,9 +67,6 @@ Object.defineProperty(exports, 'constants', {
exports.kStringMaxLength = binding.kStringMaxLength; exports.kStringMaxLength = binding.kStringMaxLength;
const kFromErrorMsg = 'First argument must be a string, Buffer, ' +
'ArrayBuffer, Array, or array-like object.';
Buffer.poolSize = 8 * 1024; Buffer.poolSize = 8 * 1024;
var poolSize, poolOffset, allocPool; var poolSize, poolOffset, allocPool;
@ -146,9 +143,8 @@ function Buffer(arg, encodingOrOffset, length) {
// Common case. // Common case.
if (typeof arg === 'number') { if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') { if (typeof encodingOrOffset === 'string') {
throw new Error( throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'string',
'If encoding is specified then the first argument must be a string' 'string', arg);
);
} }
return Buffer.alloc(arg); return Buffer.alloc(arg);
} }
@ -177,10 +173,12 @@ Buffer.from = function(value, encodingOrOffset, length) {
return fromArrayBuffer(value, encodingOrOffset, length); return fromArrayBuffer(value, encodingOrOffset, length);
if (value == null) if (value == null)
throw new TypeError(kFromErrorMsg); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
['string', 'buffer', 'arrayBuffer', 'array', 'array-like object'], value);
if (typeof value === 'number') if (typeof value === 'number')
throw new TypeError('"value" argument must not be a number'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'value', 'not number',
value);
const valueOf = value.valueOf && value.valueOf(); const valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value) if (valueOf != null && valueOf !== value)
@ -196,7 +194,8 @@ Buffer.from = function(value, encodingOrOffset, length) {
length); length);
} }
throw new TypeError(kFromErrorMsg); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
['string', 'buffer', 'arrayBuffer', 'array', 'array-like object']);
}; };
Object.setPrototypeOf(Buffer, Uint8Array); Object.setPrototypeOf(Buffer, Uint8Array);
@ -208,12 +207,11 @@ function assertSize(size) {
let err = null; let err = null;
if (typeof size !== 'number') { if (typeof size !== 'number') {
err = new TypeError('"size" argument must be a number'); err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'size', 'number', size);
} else if (size < 0) { } else if (size < 0) {
err = new RangeError('"size" argument must not be negative'); err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size);
} else if (size > binding.kMaxLength) { } else if (size > binding.kMaxLength) {
err = new RangeError('"size" argument must not be larger ' + err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size);
'than ' + binding.kMaxLength);
} }
if (err) { if (err) {
@ -300,7 +298,7 @@ function fromString(string, encoding) {
} else { } else {
length = byteLength(string, encoding, true); length = byteLength(string, encoding, true);
if (length === -1) if (length === -1)
throw new TypeError('"encoding" must be a valid string encoding'); throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
if (string.length === 0) if (string.length === 0)
return new FastBuffer(); return new FastBuffer();
} }
@ -343,7 +341,7 @@ function fromArrayBuffer(obj, byteOffset, length) {
const maxLength = obj.byteLength - byteOffset; const maxLength = obj.byteLength - byteOffset;
if (maxLength < 0) if (maxLength < 0)
throw new RangeError("'offset' is out of bounds"); throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'offset');
if (length === undefined) { if (length === undefined) {
length = maxLength; length = maxLength;
@ -355,7 +353,7 @@ function fromArrayBuffer(obj, byteOffset, length) {
length = 0; length = 0;
} else if (length > 0) { } else if (length > 0) {
if (length > maxLength) if (length > maxLength)
throw new RangeError("'length' is out of bounds"); throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length');
} else { } else {
length = 0; length = 0;
} }
@ -399,7 +397,8 @@ Buffer.isBuffer = function isBuffer(b) {
Buffer.compare = function compare(a, b) { Buffer.compare = function compare(a, b) {
if (!isUint8Array(a) || !isUint8Array(b)) { if (!isUint8Array(a) || !isUint8Array(b)) {
throw new TypeError('Arguments must be Buffers or Uint8Arrays'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', ['buf1', 'buf2'],
['buffer', 'uint8Array']);
} }
if (a === b) { if (a === b) {
@ -416,13 +415,13 @@ Buffer.isEncoding = function(encoding) {
}; };
Buffer[internalUtil.kIsEncodingSymbol] = Buffer.isEncoding; Buffer[internalUtil.kIsEncodingSymbol] = Buffer.isEncoding;
const kConcatErrMsg = '"list" argument must be an Array ' + const kConcatErr = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'list',
'of Buffer or Uint8Array instances'; ['array', 'buffer', 'uint8Array']);
Buffer.concat = function(list, length) { Buffer.concat = function(list, length) {
var i; var i;
if (!Array.isArray(list)) if (!Array.isArray(list))
throw new TypeError(kConcatErrMsg); throw kConcatErr;
if (list.length === 0) if (list.length === 0)
return new FastBuffer(); return new FastBuffer();
@ -440,7 +439,7 @@ Buffer.concat = function(list, length) {
for (i = 0; i < list.length; i++) { for (i = 0; i < list.length; i++) {
var buf = list[i]; var buf = list[i];
if (!isUint8Array(buf)) if (!isUint8Array(buf))
throw new TypeError(kConcatErrMsg); throw kConcatErr;
binding.copy(buf, buffer, pos); binding.copy(buf, buffer, pos);
pos += buf.length; pos += buf.length;
} }
@ -475,7 +474,8 @@ function byteLength(string, encoding) {
return string.byteLength; return string.byteLength;
} }
throw new TypeError('"string" must be a string, Buffer, or ArrayBuffer'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'string',
['string', 'buffer', 'arrayBuffer']);
} }
const len = string.length; const len = string.length;
@ -591,7 +591,7 @@ function stringSlice(buf, encoding, start, end) {
return buf.ucs2Slice(start, end); return buf.ucs2Slice(start, end);
break; break;
} }
throw new TypeError('Unknown encoding: ' + encoding); throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
} }
@ -633,8 +633,8 @@ Buffer.prototype.toString = function(encoding, start, end) {
Buffer.prototype.equals = function equals(b) { Buffer.prototype.equals = function equals(b) {
if (!isUint8Array(b)) if (!isUint8Array(b))
throw new TypeError('Argument must be a Buffer or Uint8Array'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'otherBuffer',
['buffer', 'uint8Array']);
if (this === b) if (this === b)
return true; return true;
@ -659,7 +659,8 @@ Buffer.prototype.compare = function compare(target,
thisStart, thisStart,
thisEnd) { thisEnd) {
if (!isUint8Array(target)) if (!isUint8Array(target))
throw new TypeError('Argument must be a Buffer or Uint8Array'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'target',
['buffer', 'uint8Array']);
if (arguments.length === 1) if (arguments.length === 1)
return compare_(this, target); return compare_(this, target);
@ -738,8 +739,8 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
return binding.indexOfNumber(buffer, val, byteOffset, dir); return binding.indexOfNumber(buffer, val, byteOffset, dir);
} }
throw new TypeError('"val" argument must be string, number, Buffer ' + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'val',
'or Uint8Array'); ['string', 'buffer', 'uint8Array']);
} }
@ -765,7 +766,7 @@ function slowIndexOf(buffer, val, byteOffset, encoding, dir) {
default: default:
if (loweredCase) { if (loweredCase) {
throw new TypeError('Unknown encoding: ' + encoding); throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
} }
encoding = ('' + encoding).toLowerCase(); encoding = ('' + encoding).toLowerCase();
@ -807,11 +808,11 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) {
} }
if (encoding !== undefined && typeof encoding !== 'string') { if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string'); throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding', 'string');
} }
var normalizedEncoding = internalUtil.normalizeEncoding(encoding); var normalizedEncoding = internalUtil.normalizeEncoding(encoding);
if (normalizedEncoding === undefined) { if (normalizedEncoding === undefined) {
throw new TypeError('Unknown encoding: ' + encoding); throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
} }
if (val.length === 0) { if (val.length === 0) {
@ -872,13 +873,13 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
length = remaining; length = remaining;
if (string.length > 0 && (length < 0 || offset < 0)) if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('Attempt to write outside buffer bounds'); throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length', true);
} else { } else {
// if someone is still calling the obsolete form of write(), tell them. // if someone is still calling the obsolete form of write(), tell them.
// we don't want eg buf.write("foo", "utf8", 10) to silently turn into // we don't want eg buf.write("foo", "utf8", 10) to silently turn into
// buf.write("foo", "utf8"), so we can't ignore extra args // buf.write("foo", "utf8"), so we can't ignore extra args
throw new Error('Buffer.write(string, encoding, offset[, length]) ' + throw new errors.Error('ERR_NO_LONGER_SUPPORTED',
'is no longer supported'); 'Buffer.write(string, encoding, offset[, length])');
} }
if (!encoding) return this.utf8Write(string, offset, length); if (!encoding) return this.utf8Write(string, offset, length);
@ -925,7 +926,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
return this.hexWrite(string, offset, length); return this.hexWrite(string, offset, length);
break; break;
} }
throw new TypeError('Unknown encoding: ' + encoding); throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding);
}; };
@ -1176,7 +1177,7 @@ Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
function checkInt(buffer, value, offset, ext, max, min) { function checkInt(buffer, value, offset, ext, max, min) {
if (value > max || value < min) if (value > max || value < min)
throw new TypeError('"value" argument is out of bounds'); throw new errors.RangeError('ERR_INVALID_OPT_VALUE', 'value', value);
if (offset + ext > buffer.length) if (offset + ext > buffer.length)
throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE');
} }
@ -1448,7 +1449,7 @@ Buffer.prototype.swap16 = function swap16() {
// dropping down to the native code is faster. // dropping down to the native code is faster.
const len = this.length; const len = this.length;
if (len % 2 !== 0) if (len % 2 !== 0)
throw new RangeError('Buffer size must be a multiple of 16-bits'); throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '16-bits');
if (len < 128) { if (len < 128) {
for (var i = 0; i < len; i += 2) for (var i = 0; i < len; i += 2)
swap(this, i, i + 1); swap(this, i, i + 1);
@ -1464,7 +1465,7 @@ Buffer.prototype.swap32 = function swap32() {
// dropping down to the native code is faster. // dropping down to the native code is faster.
const len = this.length; const len = this.length;
if (len % 4 !== 0) if (len % 4 !== 0)
throw new RangeError('Buffer size must be a multiple of 32-bits'); throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '32-bits');
if (len < 192) { if (len < 192) {
for (var i = 0; i < len; i += 4) { for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3); swap(this, i, i + 3);
@ -1482,7 +1483,7 @@ Buffer.prototype.swap64 = function swap64() {
// dropping down to the native code is faster. // dropping down to the native code is faster.
const len = this.length; const len = this.length;
if (len % 8 !== 0) if (len % 8 !== 0)
throw new RangeError('Buffer size must be a multiple of 64-bits'); throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '64-bits');
if (len < 192) { if (len < 192) {
for (var i = 0; i < len; i += 8) { for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7); swap(this, i, i + 7);

View file

@ -109,9 +109,11 @@ module.exports = exports = {
// Note: Please try to keep these in alphabetical order // Note: Please try to keep these in alphabetical order
E('ERR_ARG_NOT_ITERABLE', '%s must be iterable'); E('ERR_ARG_NOT_ITERABLE', '%s must be iterable');
E('ERR_ASSERTION', '%s'); E('ERR_ASSERTION', '%s');
E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds);
E('ERR_CONSOLE_WRITABLE_STREAM', E('ERR_CONSOLE_WRITABLE_STREAM',
'Console expects a writable stream instance for %s'); 'Console expects a writable stream instance for %s');
E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s'); E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s');
E('ERR_NO_LONGER_SUPPORTED', '%s is no longer supported');
E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value'); E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value');
E('ERR_HTTP_HEADERS_SENT', E('ERR_HTTP_HEADERS_SENT',
'Cannot render headers after they are sent to the client'); 'Cannot render headers after they are sent to the client');
@ -127,6 +129,7 @@ E('ERR_INVALID_ARRAY_LENGTH',
return `The "${name}" array must have a length of ${ return `The "${name}" array must have a length of ${
length}. Received length ${actual}`; length}. Received length ${actual}`;
}); });
E('ERR_INVALID_BUFFER_SIZE', 'Buffer size must be a multiple of %s');
E('ERR_INVALID_CALLBACK', 'Callback must be a function'); E('ERR_INVALID_CALLBACK', 'Callback must be a function');
E('ERR_INVALID_CHAR', 'Invalid character in %s'); E('ERR_INVALID_CHAR', 'Invalid character in %s');
E('ERR_INVALID_CURSOR_POS', E('ERR_INVALID_CURSOR_POS',
@ -173,6 +176,7 @@ E('ERR_TRANSFORM_ALREADY_TRANSFORMING',
'Calling transform done when still transforming'); 'Calling transform done when still transforming');
E('ERR_TRANSFORM_WITH_LENGTH_0', E('ERR_TRANSFORM_WITH_LENGTH_0',
'Calling transform done when writableState.length != 0'); 'Calling transform done when writableState.length != 0');
E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s');
E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s'); E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s');
E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type'); E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type');
E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type'); E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type');
@ -183,8 +187,29 @@ E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. ' +
function invalidArgType(name, expected, actual) { function invalidArgType(name, expected, actual) {
const assert = lazyAssert(); const assert = lazyAssert();
assert(name, 'name is required'); assert(name, 'name is required');
const type = name.includes('.') ? 'property' : 'argument';
var msg = `The "${name}" ${type} must be ${oneOf(expected, 'type')}`; // determiner: 'must be' or 'must not be'
let determiner;
if (expected.includes('not ')) {
determiner = 'must not be';
expected = expected.split('not ')[1];
} else {
determiner = 'must be';
}
let msg;
if (Array.isArray(name)) {
var names = name.map((val) => `"${val}"`).join(', ');
msg = `The ${names} arguments ${determiner} ${oneOf(expected, 'type')}`;
} else if (name.includes(' argument')) {
// for the case like 'first argument'
msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
} else {
const type = name.includes('.') ? 'property' : 'argument';
msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
}
// if actual value received, output it
if (arguments.length >= 3) { if (arguments.length >= 3) {
msg += `. Received type ${actual !== null ? typeof actual : 'null'}`; msg += `. Received type ${actual !== null ? typeof actual : 'null'}`;
} }
@ -231,3 +256,11 @@ function oneOf(expected, thing) {
return `of ${thing} ${String(expected)}`; return `of ${thing} ${String(expected)}`;
} }
} }
function bufferOutOfBounds(name, isWriting) {
if (isWriting) {
return 'Attempt to write outside buffer bounds';
} else {
return `"${name}" is outside of buffer bounds`;
}
}

View file

@ -27,7 +27,6 @@ const assert = require('assert');
const os = require('os'); const os = require('os');
const child_process = require('child_process'); const child_process = require('child_process');
const stream = require('stream'); const stream = require('stream');
const buffer = require('buffer');
const util = require('util'); const util = require('util');
const Timer = process.binding('timer_wrap').Timer; const Timer = process.binding('timer_wrap').Timer;
const execSync = require('child_process').execSync; const execSync = require('child_process').execSync;
@ -54,8 +53,6 @@ exports.isLinux = process.platform === 'linux';
exports.isOSX = process.platform === 'darwin'; exports.isOSX = process.platform === 'darwin';
exports.enoughTestMem = os.totalmem() > 0x40000000; /* 1 Gb */ exports.enoughTestMem = os.totalmem() > 0x40000000; /* 1 Gb */
exports.bufferMaxSizeMsg = new RegExp(
`^RangeError: "size" argument must not be larger than ${buffer.kMaxLength}$`);
const cpus = os.cpus(); const cpus = os.cpus();
exports.enoughTestCpu = Array.isArray(cpus) && exports.enoughTestCpu = Array.isArray(cpus) &&
(cpus.length > 1 || cpus[0].speed > 999); (cpus.length > 1 || cpus[0].speed > 999);

View file

@ -888,7 +888,11 @@ assert.throws(() => Buffer.allocUnsafe(8).writeFloatLE(0.0, -1), RangeError);
// Regression test for #5482: should throw but not assert in C++ land. // Regression test for #5482: should throw but not assert in C++ land.
assert.throws(() => Buffer.from('', 'buffer'), assert.throws(() => Buffer.from('', 'buffer'),
/^TypeError: "encoding" must be a valid string encoding$/); common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: buffer'
}));
// Regression test for #6111. Constructing a buffer from another buffer // Regression test for #6111. Constructing a buffer from another buffer
// should a) work, and b) not corrupt the source buffer. // should a) work, and b) not corrupt the source buffer.
@ -930,7 +934,8 @@ assert.throws(() => Buffer.allocUnsafe(10).copy(),
/TypeError: argument should be a Buffer/); /TypeError: argument should be a Buffer/);
const regErrorMsg = const regErrorMsg =
/First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object\./; new RegExp('The first argument must be one of type string, buffer, ' +
'arrayBuffer, array, or array-like object\\.');
assert.throws(() => Buffer.from(), regErrorMsg); assert.throws(() => Buffer.from(), regErrorMsg);
assert.throws(() => Buffer.from(null), regErrorMsg); assert.throws(() => Buffer.from(null), regErrorMsg);
@ -957,8 +962,14 @@ assert.strictEqual(SlowBuffer.prototype.offset, undefined);
// Test that ParseArrayIndex handles full uint32 // Test that ParseArrayIndex handles full uint32
assert.throws(() => Buffer.from(new ArrayBuffer(0), -1 >>> 0), {
/RangeError: 'offset' is out of bounds/); const errMsg = common.expectsError({
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
message: '"offset" is outside of buffer bounds'
});
assert.throws(() => Buffer.from(new ArrayBuffer(0), -1 >>> 0), errMsg);
}
// ParseArrayIndex() should reject values that don't fit in a 32 bits size_t. // ParseArrayIndex() should reject values that don't fit in a 32 bits size_t.
assert.throws(() => { assert.throws(() => {
@ -985,9 +996,9 @@ assert.doesNotThrow(() => Buffer.from(arrayBuf));
assert.doesNotThrow(() => Buffer.from({ buffer: arrayBuf })); assert.doesNotThrow(() => Buffer.from({ buffer: arrayBuf }));
assert.throws(() => Buffer.alloc({ valueOf: () => 1 }), assert.throws(() => Buffer.alloc({ valueOf: () => 1 }),
/"size" argument must be a number/); /"size" argument must be of type number/);
assert.throws(() => Buffer.alloc({ valueOf: () => -1 }), assert.throws(() => Buffer.alloc({ valueOf: () => -1 }),
/"size" argument must be a number/); /"size" argument must be of type number/);
assert.strictEqual(Buffer.prototype.toLocaleString, Buffer.prototype.toString); assert.strictEqual(Buffer.prototype.toLocaleString, Buffer.prototype.toString);
{ {

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const LENGTH = 16; const LENGTH = 16;
@ -65,16 +65,16 @@ b.writeDoubleBE(11.11, 0, true);
buf[0] = 9; buf[0] = 9;
assert.strictEqual(ab[1], 9); assert.strictEqual(ab[1], 9);
assert.throws(() => Buffer.from(ab.buffer, 6), (err) => { assert.throws(() => Buffer.from(ab.buffer, 6), common.expectsError({
assert(err instanceof RangeError); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
assert(/'offset' is out of bounds/.test(err.message)); type: RangeError,
return true; message: '"offset" is outside of buffer bounds'
}); }));
assert.throws(() => Buffer.from(ab.buffer, 3, 6), (err) => { assert.throws(() => Buffer.from(ab.buffer, 3, 6), common.expectsError({
assert(err instanceof RangeError); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
assert(/'length' is out of bounds/.test(err.message)); type: RangeError,
return true; message: '"length" is outside of buffer bounds'
}); }));
} }
// Test the deprecated Buffer() version also // Test the deprecated Buffer() version also
@ -93,16 +93,16 @@ b.writeDoubleBE(11.11, 0, true);
buf[0] = 9; buf[0] = 9;
assert.strictEqual(ab[1], 9); assert.strictEqual(ab[1], 9);
assert.throws(() => Buffer(ab.buffer, 6), (err) => { assert.throws(() => Buffer(ab.buffer, 6), common.expectsError({
assert(err instanceof RangeError); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
assert(/'offset' is out of bounds/.test(err.message)); type: RangeError,
return true; message: '"offset" is outside of buffer bounds'
}); }));
assert.throws(() => Buffer(ab.buffer, 3, 6), (err) => { assert.throws(() => Buffer(ab.buffer, 3, 6), common.expectsError({
assert(err instanceof RangeError); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
assert(/'length' is out of bounds/.test(err.message)); type: RangeError,
return true; message: '"length" is outside of buffer bounds'
}); }));
} }
{ {
@ -118,10 +118,13 @@ b.writeDoubleBE(11.11, 0, true);
assert.deepStrictEqual(Buffer.from(ab, [1]), Buffer.from(ab, 1)); assert.deepStrictEqual(Buffer.from(ab, [1]), Buffer.from(ab, 1));
// If byteOffset is Infinity, throw. // If byteOffset is Infinity, throw.
assert.throws( assert.throws(() => {
() => { Buffer.from(ab, Infinity); }, Buffer.from(ab, Infinity);
/^RangeError: 'offset' is out of bounds$/ }, common.expectsError({
); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
message: '"offset" is outside of buffer bounds'
}));
} }
{ {
@ -137,8 +140,11 @@ b.writeDoubleBE(11.11, 0, true);
assert.deepStrictEqual(Buffer.from(ab, 0, [1]), Buffer.from(ab, 0, 1)); assert.deepStrictEqual(Buffer.from(ab, 0, [1]), Buffer.from(ab, 0, 1));
//If length is Infinity, throw. //If length is Infinity, throw.
assert.throws( assert.throws(() => {
() => { Buffer.from(ab, 0, Infinity); }, Buffer.from(ab, 0, Infinity);
/^RangeError: 'length' is out of bounds$/ }, common.expectsError({
); code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
message: '"length" is outside of buffer bounds'
}));
} }

View file

@ -1,14 +1,20 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
assert.doesNotThrow(function() { assert.doesNotThrow(function() {
Buffer.allocUnsafe(10); Buffer.allocUnsafe(10);
}); });
const err = common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "value" argument must not be of type number. ' +
'Received type number'
});
assert.throws(function() { assert.throws(function() {
Buffer.from(10, 'hex'); Buffer.from(10, 'hex');
}, /^TypeError: "value" argument must not be a number$/); }, err);
assert.doesNotThrow(function() { assert.doesNotThrow(function() {
Buffer.from('deadbeaf', 'hex'); Buffer.from('deadbeaf', 'hex');

View file

@ -1,16 +1,21 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const SlowBuffer = require('buffer').SlowBuffer; const SlowBuffer = require('buffer').SlowBuffer;
const vm = require('vm'); const vm = require('vm');
// coerce values to string // coerce values to string
const re = /"string" must be a string, Buffer, or ArrayBuffer/; const errMsg = common.expectsError({
assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, re); code: 'ERR_INVALID_ARG_TYPE',
assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, re); type: TypeError,
assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, re); message: 'The "string" argument must be one of type string, ' +
assert.throws(() => { Buffer.byteLength(); }, re); 'buffer, or arrayBuffer'
}, 4);
assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, errMsg);
assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, errMsg);
assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, errMsg);
assert.throws(() => { Buffer.byteLength(); }, errMsg);
assert.strictEqual(Buffer.byteLength('', undefined, true), -1); assert.strictEqual(Buffer.byteLength('', undefined, true), -1);

View file

@ -66,4 +66,8 @@ assert.throws(() => a.compare(b, 0, '0xff'), oor);
assert.throws(() => a.compare(b, 0, Infinity), oor); assert.throws(() => a.compare(b, 0, Infinity), oor);
assert.throws(() => a.compare(b, 0, 1, -1), oor); assert.throws(() => a.compare(b, 0, 1, -1), oor);
assert.throws(() => a.compare(b, -Infinity, Infinity), oor); assert.throws(() => a.compare(b, -Infinity, Infinity), oor);
assert.throws(() => a.compare(), /Argument must be a Buffer/); assert.throws(() => a.compare(), common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "target" argument must be one of type buffer or uint8Array'
}));

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const b = Buffer.alloc(1, 'a'); const b = Buffer.alloc(1, 'a');
@ -28,11 +28,18 @@ assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0)), 0);
assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1); assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1);
assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1); assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1);
assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), const errMsg = common.expectsError({
/^TypeError: Arguments must be Buffers or Uint8Arrays$/); code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "buf1", "buf2" arguments must be one of ' +
'type buffer or uint8Array'
}, 2);
assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg);
assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), errMsg);
/^TypeError: Arguments must be Buffers or Uint8Arrays$/);
assert.throws(() => Buffer.alloc(1).compare('abc'), assert.throws(() => Buffer.alloc(1).compare('abc'), common.expectsError({
/^TypeError: Argument must be a Buffer or Uint8Array$/); code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "target" argument must be one of type buffer or uint8Array'
}));

View file

@ -54,11 +54,12 @@ assertWrongList(['hello', Buffer.from('world')]);
function assertWrongList(value) { function assertWrongList(value) {
assert.throws(() => { assert.throws(() => {
Buffer.concat(value); Buffer.concat(value);
}, function(err) { }, common.expectsError({
return err instanceof TypeError && code: 'ERR_INVALID_ARG_TYPE',
err.message === '"list" argument must be an Array of Buffer ' + type: TypeError,
'or Uint8Array instances'; message: 'The "list" argument must be one of type ' +
}); 'array, buffer, or uint8Array'
}));
} }
const random10 = common.hasCrypto ? const random10 = common.hasCrypto ?

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const b = Buffer.from('abcdf'); const b = Buffer.from('abcdf');
@ -15,4 +15,9 @@ assert.ok(d.equals(d));
assert.ok(d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]))); assert.ok(d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65])));
assert.throws(() => Buffer.alloc(1).equals('abc'), assert.throws(() => Buffer.alloc(1).equals('abc'),
/^TypeError: Argument must be a Buffer or Uint8Array$/); common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "otherBuffer" argument must be one of type ' +
'buffer or uint8Array'
}));

View file

@ -206,16 +206,30 @@ assert.throws(
common.expectsError({code: 'ERR_INDEX_OUT_OF_RANGE'})); common.expectsError({code: 'ERR_INDEX_OUT_OF_RANGE'}));
assert.throws( assert.throws(
() => buf1.fill('a', 0, buf1.length, 'node rocks!'), () => buf1.fill('a', 0, buf1.length, 'node rocks!'),
/^TypeError: Unknown encoding: node rocks!$/); common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: node rocks!'
}));
assert.throws( assert.throws(
() => buf1.fill('a', 0, 0, NaN), () => buf1.fill('a', 0, 0, NaN),
/^TypeError: encoding must be a string$/); common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "encoding" argument must be of type string'
}));
assert.throws( assert.throws(
() => buf1.fill('a', 0, 0, null), () => buf1.fill('a', 0, 0, null),
/^TypeError: encoding must be a string$/); common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "encoding" argument must be of type string'
}));
assert.throws( assert.throws(
() => buf1.fill('a', 0, 0, 'foo'), () => buf1.fill('a', 0, 0, 'foo'),
/^TypeError: Unknown encoding: foo$/); common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: foo'
}));
function genBuffer(size, args) { function genBuffer(size, args) {

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const { deepStrictEqual, throws } = require('assert'); const { deepStrictEqual, throws } = require('assert');
const { Buffer } = require('buffer'); const { Buffer } = require('buffer');
const { runInNewContext } = require('vm'); const { runInNewContext } = require('vm');
@ -34,9 +34,6 @@ deepStrictEqual(Buffer.from(
runInNewContext('new String(checkString)', {checkString})), runInNewContext('new String(checkString)', {checkString})),
check); check);
const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' +
'ArrayBuffer, Array, or array-like object\\.$');
[ [
{}, {},
new Boolean(true), new Boolean(true),
@ -45,6 +42,12 @@ const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' +
{ valueOf: null }, { valueOf: null },
Object.create(null) Object.create(null)
].forEach((input) => { ].forEach((input) => {
const err = common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The first argument must be one of type string, buffer, ' +
'arrayBuffer, array, or array-like object'
});
throws(() => Buffer.from(input), err); throws(() => Buffer.from(input), err);
}); });
@ -52,6 +55,11 @@ const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' +
new Number(true), new Number(true),
new MyBadPrimitive() new MyBadPrimitive()
].forEach((input) => { ].forEach((input) => {
throws(() => Buffer.from(input), const errMsg = common.expectsError({
/^TypeError: "value" argument must not be a number$/); code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "value" argument must not be of type number. ' +
'Received type number'
});
throws(() => Buffer.from(input), errMsg);
}); });

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common');
const assert = require('assert'); const assert = require('assert');
const common = require('../common');
const b = Buffer.from('abcdef'); const b = Buffer.from('abcdef');
const buf_a = Buffer.from('a'); const buf_a = Buffer.from('a');
@ -271,8 +271,12 @@ for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
} }
} }
const expectedError = const expectedError = common.expectsError({
/^TypeError: "val" argument must be string, number, Buffer or Uint8Array$/; code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "val" argument must be one of type ' +
'string, buffer, or uint8Array'
}, 3);
assert.throws(() => { assert.throws(() => {
b.includes(() => {}); b.includes(() => {});
}, expectedError); }, expectedError);

View file

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const b = Buffer.from('abcdef'); const b = Buffer.from('abcdef');
@ -344,8 +344,12 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
} }
} }
const argumentExpected = const argumentExpected = common.expectsError({
/^TypeError: "val" argument must be string, number, Buffer or Uint8Array$/; code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "val" argument must be one of type ' +
'string, buffer, or uint8Array'
}, 3);
assert.throws(() => { assert.throws(() => {
b.indexOf(() => { }); b.indexOf(() => { });

View file

@ -0,0 +1,17 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const SlowBuffer = require('buffer').SlowBuffer;
const bufferNegativeMsg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "size"$/
}, 5);
assert.throws(() => Buffer(-1).toString('utf8'), bufferNegativeMsg);
assert.throws(() => SlowBuffer(-1).toString('utf8'), bufferNegativeMsg);
assert.throws(() => Buffer.alloc(-1).toString('utf8'), bufferNegativeMsg);
assert.throws(() => Buffer.allocUnsafe(-1).toString('utf8'), bufferNegativeMsg);
assert.throws(() => Buffer.allocUnsafeSlow(-1).toString('utf8'),
bufferNegativeMsg);

View file

@ -1,6 +1,11 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
assert.throws(() => new Buffer(42, 'utf8'), /first argument must be a string/); assert.throws(() => new Buffer(42, 'utf8'), common.expectsError({
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'The "string" argument must be of type string. ' +
'Received type number'
}));

View file

@ -1,9 +1,13 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const msg = /"size" argument must not be negative/; const msg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "size"$/
}, 12);
// Test that negative Buffer length inputs throw errors. // Test that negative Buffer length inputs throw errors.

View file

@ -7,7 +7,11 @@ const Buffer = buffer.Buffer;
const SlowBuffer = buffer.SlowBuffer; const SlowBuffer = buffer.SlowBuffer;
const kMaxLength = buffer.kMaxLength; const kMaxLength = buffer.kMaxLength;
const bufferMaxSizeMsg = common.bufferMaxSizeMsg; const bufferMaxSizeMsg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "size"$/
}, 12);
assert.throws(() => Buffer((-1 >>> 0) + 1), bufferMaxSizeMsg); assert.throws(() => Buffer((-1 >>> 0) + 1), bufferMaxSizeMsg);
assert.throws(() => SlowBuffer((-1 >>> 0) + 1), bufferMaxSizeMsg); assert.throws(() => SlowBuffer((-1 >>> 0) + 1), bufferMaxSizeMsg);

View file

@ -6,7 +6,11 @@ const SlowBuffer = require('buffer').SlowBuffer;
// Regression test for https://github.com/nodejs/node/issues/649. // Regression test for https://github.com/nodejs/node/issues/649.
const len = 1422561062959; const len = 1422561062959;
const message = common.bufferMaxSizeMsg; const message = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "size"$/
}, 5);
assert.throws(() => Buffer(len).toString('utf8'), message); assert.throws(() => Buffer(len).toString('utf8'), message);
assert.throws(() => SlowBuffer(len).toString('utf8'), message); assert.throws(() => SlowBuffer(len).toString('utf8'), message);
assert.throws(() => Buffer.alloc(len).toString('utf8'), message); assert.throws(() => Buffer.alloc(len).toString('utf8'), message);

View file

@ -48,12 +48,22 @@ assert.strictEqual(SlowBuffer({}).length, 0);
assert.strictEqual(SlowBuffer('string').length, 0); assert.strictEqual(SlowBuffer('string').length, 0);
// should throw with invalid length // should throw with invalid length
const bufferMaxSizeMsg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "size"$/
}, 2);
assert.throws(function() { assert.throws(function() {
SlowBuffer(Infinity); SlowBuffer(Infinity);
}, common.bufferMaxSizeMsg); }, bufferMaxSizeMsg);
assert.throws(function() { assert.throws(function() {
SlowBuffer(-1); SlowBuffer(-1);
}, /^RangeError: "size" argument must not be negative$/); }, common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: 'The value "-1" is invalid for option "size"'
}));
assert.throws(function() { assert.throws(function() {
SlowBuffer(buffer.kMaxLength + 1); SlowBuffer(buffer.kMaxLength + 1);
}, common.bufferMaxSizeMsg); }, bufferMaxSizeMsg);

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const rangeBuffer = Buffer.from('abc'); const rangeBuffer = Buffer.from('abc');
@ -86,7 +86,15 @@ assert.strictEqual(rangeBuffer.toString({toString: function() {
// try toString() with 0 and null as the encoding // try toString() with 0 and null as the encoding
assert.throws(() => { assert.throws(() => {
rangeBuffer.toString(0, 1, 2); rangeBuffer.toString(0, 1, 2);
}, /^TypeError: Unknown encoding: 0$/); }, common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: 0'
}));
assert.throws(() => { assert.throws(() => {
rangeBuffer.toString(null, 1, 2); rangeBuffer.toString(null, 1, 2);
}, /^TypeError: Unknown encoding: null$/); }, common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: null'
}));

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
// utf8, ucs2, ascii, latin1, utf16le // utf8, ucs2, ascii, latin1, utf16le
@ -27,8 +27,11 @@ encodings
// Invalid encodings // Invalid encodings
for (let i = 1; i < 10; i++) { for (let i = 1; i < 10; i++) {
const encoding = String(i).repeat(i); const encoding = String(i).repeat(i);
const error = new RegExp(`^TypeError: Unknown encoding: ${encoding}$`); const error = common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: `Unknown encoding: ${encoding}`
});
assert.ok(!Buffer.isEncoding(encoding)); assert.ok(!Buffer.isEncoding(encoding));
assert.throws(() => Buffer.from('foo').toString(encoding), error); assert.throws(() => Buffer.from('foo').toString(encoding), error);
} }

View file

@ -1,9 +1,13 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const outsideBounds = /^RangeError: Attempt to write outside buffer bounds$/; const outsideBounds = common.expectsError({
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
message: 'Attempt to write outside buffer bounds'
}, 2);
assert.throws(() => Buffer.alloc(9).write('foo', -1), outsideBounds); assert.throws(() => Buffer.alloc(9).write('foo', -1), outsideBounds);
assert.throws(() => Buffer.alloc(9).write('foo', 10), outsideBounds); assert.throws(() => Buffer.alloc(9).write('foo', 10), outsideBounds);
@ -57,7 +61,11 @@ encodings
// Invalid encodings // Invalid encodings
for (let i = 1; i < 10; i++) { for (let i = 1; i < 10; i++) {
const encoding = String(i).repeat(i); const encoding = String(i).repeat(i);
const error = new RegExp(`^TypeError: Unknown encoding: ${encoding}$`); const error = common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: `Unknown encoding: ${encoding}`
});
assert.ok(!Buffer.isEncoding(encoding)); assert.ok(!Buffer.isEncoding(encoding));
assert.throws(() => Buffer.alloc(9).write('foo', encoding), error); assert.throws(() => Buffer.alloc(9).write('foo', encoding), error);

View file

@ -255,7 +255,7 @@ const values = [
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "last argument" argument must be of type function' message: 'The last argument must be of type function'
})); }));
}); });
} }

View file

@ -23,9 +23,13 @@
/* /*
* Tests to verify we're writing signed integers correctly * Tests to verify we're writing signed integers correctly
*/ */
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const errorOutOfBounds = /^TypeError: "value" argument is out of bounds$/; const errorOutOfBounds = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "value"$/
}, 12);
function test8(clazz) { function test8(clazz) {
const buffer = new clazz(2); const buffer = new clazz(2);

View file

@ -23,7 +23,7 @@
/* /*
* A battery of tests to help us read a series of uints * A battery of tests to help us read a series of uints
*/ */
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
/* /*
@ -149,13 +149,17 @@ function testUint(clazz) {
// Test 0 to 5 bytes. // Test 0 to 5 bytes.
for (let i = 0; i <= 5; i++) { for (let i = 0; i <= 5; i++) {
const errmsg = `byteLength: ${i}`; const errMsg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
message: /^The value "[^"]*" is invalid for option "value"$/
}, 2);
assert.throws(function() { assert.throws(function() {
data.writeUIntBE(val, 0, i); data.writeUIntBE(val, 0, i);
}, /"value" argument is out of bounds/, errmsg); }, errMsg);
assert.throws(function() { assert.throws(function() {
data.writeUIntLE(val, 0, i); data.writeUIntLE(val, 0, i);
}, /"value" argument is out of bounds/, errmsg); }, errMsg);
val *= 0x100; val *= 0x100;
} }
} }