From 2fce9d69816c4713ad1a2075422bf8d94d2c95b1 Mon Sep 17 00:00:00 2001 From: sungpaks Date: Tue, 20 Aug 2024 17:22:26 +0900 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/19445 --- lib/buffer.js | 8 +++----- test/parallel/test-buffer-concat.js | 14 +++++++------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 05b57275f03dca..ede489749176c5 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -583,7 +583,7 @@ Buffer.concat = function concat(list, length) { if (length === undefined) { length = 0; for (let i = 0; i < list.length; i++) { - if (list[i].length) { + if (list[i]?.length) { length += list[i].length; } } @@ -596,10 +596,8 @@ Buffer.concat = function concat(list, length) { for (let i = 0; i < list.length; i++) { const buf = list[i]; if (!isUint8Array(buf)) { - // TODO(BridgeAR): This should not be of type ERR_INVALID_ARG_TYPE. - // Instead, find the proper error code for this. - throw new ERR_INVALID_ARG_TYPE( - `list[${i}]`, ['Buffer', 'Uint8Array'], list[i]); + throw new ERR_INVALID_ARG_VALUE( + `list[${i}]`, buf, 'must be of type Buffer or Uint8Array'); } pos += _copyActual(buf, buffer, pos, 0, buf.length); } diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js index 2e7541fb58b063..3874db7bfccc8b 100644 --- a/test/parallel/test-buffer-concat.js +++ b/test/parallel/test-buffer-concat.js @@ -54,22 +54,22 @@ assert.strictEqual(flatLongLen.toString(), check); }); }); -[[42], ['hello', Buffer.from('world')]].forEach((value) => { +[[42], [null], [undefined], ['hello', Buffer.from('world')]].forEach((value) => { assert.throws(() => { Buffer.concat(value); }, { - code: 'ERR_INVALID_ARG_TYPE', - message: 'The "list[0]" argument must be an instance of Buffer ' + - `or Uint8Array.${common.invalidArgTypeHelper(value[0])}` + code: 'ERR_INVALID_ARG_VALUE', + message: 'The argument \'list[0]\' must be of type Buffer ' + + `or Uint8Array. Received ${typeof value[0] === 'string' ? `'${value[0]}'` : value[0]}` }); }); assert.throws(() => { Buffer.concat([Buffer.from('hello'), 3]); }, { - code: 'ERR_INVALID_ARG_TYPE', - message: 'The "list[1]" argument must be an instance of Buffer ' + - 'or Uint8Array. Received type number (3)' + code: 'ERR_INVALID_ARG_VALUE', + message: 'The argument \'list[1]\' must be of type Buffer ' + + 'or Uint8Array. Received 3' }); // eslint-disable-next-line node-core/crypto-check