Skip to content

Commit 2fce9d6

Browse files
committed
buffer: improve error handling of buffer.concat
Resolved TODO to use more proper error code INVALID_ARG_TYPE -> INVALID_ARG_VALUE, it seems better Additionally, when the `list` argument has null or undefined and the `length` argument is undefined, it causes `TypeError: Cannot read properties` error. It has been adjusted to be handled by the INVALID_ARG_VALUE error. Refs: nodejs#19445
1 parent ef4bdbf commit 2fce9d6

2 files changed

Lines changed: 10 additions & 12 deletions

File tree

lib/buffer.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -583,7 +583,7 @@ Buffer.concat = function concat(list, length) {
583583
if (length === undefined) {
584584
length = 0;
585585
for (let i = 0; i < list.length; i++) {
586-
if (list[i].length) {
586+
if (list[i]?.length) {
587587
length += list[i].length;
588588
}
589589
}
@@ -596,10 +596,8 @@ Buffer.concat = function concat(list, length) {
596596
for (let i = 0; i < list.length; i++) {
597597
const buf = list[i];
598598
if (!isUint8Array(buf)) {
599-
// TODO(BridgeAR): This should not be of type ERR_INVALID_ARG_TYPE.
600-
// Instead, find the proper error code for this.
601-
throw new ERR_INVALID_ARG_TYPE(
602-
`list[${i}]`, ['Buffer', 'Uint8Array'], list[i]);
599+
throw new ERR_INVALID_ARG_VALUE(
600+
`list[${i}]`, buf, 'must be of type Buffer or Uint8Array');
603601
}
604602
pos += _copyActual(buf, buffer, pos, 0, buf.length);
605603
}

test/parallel/test-buffer-concat.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,22 +54,22 @@ assert.strictEqual(flatLongLen.toString(), check);
5454
});
5555
});
5656

57-
[[42], ['hello', Buffer.from('world')]].forEach((value) => {
57+
[[42], [null], [undefined], ['hello', Buffer.from('world')]].forEach((value) => {
5858
assert.throws(() => {
5959
Buffer.concat(value);
6060
}, {
61-
code: 'ERR_INVALID_ARG_TYPE',
62-
message: 'The "list[0]" argument must be an instance of Buffer ' +
63-
`or Uint8Array.${common.invalidArgTypeHelper(value[0])}`
61+
code: 'ERR_INVALID_ARG_VALUE',
62+
message: 'The argument \'list[0]\' must be of type Buffer ' +
63+
`or Uint8Array. Received ${typeof value[0] === 'string' ? `'${value[0]}'` : value[0]}`
6464
});
6565
});
6666

6767
assert.throws(() => {
6868
Buffer.concat([Buffer.from('hello'), 3]);
6969
}, {
70-
code: 'ERR_INVALID_ARG_TYPE',
71-
message: 'The "list[1]" argument must be an instance of Buffer ' +
72-
'or Uint8Array. Received type number (3)'
70+
code: 'ERR_INVALID_ARG_VALUE',
71+
message: 'The argument \'list[1]\' must be of type Buffer ' +
72+
'or Uint8Array. Received 3'
7373
});
7474

7575
// eslint-disable-next-line node-core/crypto-check

0 commit comments

Comments
 (0)