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' } ); {