From 3ce51ae9c08fb1281591f563568d760192ea07a2 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Tue, 4 Jul 2023 11:52:56 +0200 Subject: [PATCH] module: harmonize error code between ESM and CJS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/48606 Reviewed-By: Yagiz Nizipli Reviewed-By: Jan Krems Reviewed-By: Michaƫl Zasso Reviewed-By: Matteo Collina --- lib/internal/modules/package_json_reader.js | 24 ++++++++------------- test/sequential/test-module-loading.js | 2 +- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js index c6377faae6f5a8..0572147d5e5897 100644 --- a/lib/internal/modules/package_json_reader.js +++ b/lib/internal/modules/package_json_reader.js @@ -10,7 +10,7 @@ const { } = require('internal/errors').codes; const { internalModuleReadJSON } = internalBinding('fs'); const { toNamespacedPath } = require('path'); -const { kEmptyObject } = require('internal/util'); +const { kEmptyObject, setOwnProperty } = require('internal/util'); const { fileURLToPath, pathToFileURL } = require('internal/url'); @@ -73,20 +73,14 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) { let parsed; try { parsed = JSONParse(string); - } catch (error) { - if (isESM) { - throw new ERR_INVALID_PACKAGE_CONFIG( - jsonPath, - (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier), - error.message, - ); - } else { - // For backward compat, we modify the error returned by JSON.parse rather than creating a new one. - // TODO(aduh95): make it throw ERR_INVALID_PACKAGE_CONFIG in a semver-major with original error as cause - error.message = 'Error parsing ' + jsonPath + ': ' + error.message; - error.path = jsonPath; - throw error; - } + } catch (cause) { + const error = new ERR_INVALID_PACKAGE_CONFIG( + jsonPath, + isESM && (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier), + cause.message, + ); + setOwnProperty(error, 'cause', cause); + throw error; } result.exists = true; diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index ebbbcbb6c937ef..1020539827b913 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -128,7 +128,7 @@ assert.throws( assert.throws( function() { require('../fixtures/packages/unparseable'); }, - /^SyntaxError: Error parsing/ + { code: 'ERR_INVALID_PACKAGE_CONFIG' } ); {