Skip to content

Commit 3ce51ae

Browse files
authored
module: harmonize error code between ESM and CJS
PR-URL: #48606 Reviewed-By: Yagiz Nizipli <[email protected]> Reviewed-By: Jan Krems <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Matteo Collina <[email protected]>
1 parent 586fcff commit 3ce51ae

File tree

2 files changed

+10
-16
lines changed

2 files changed

+10
-16
lines changed

lib/internal/modules/package_json_reader.js

+9-15
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const {
1010
} = require('internal/errors').codes;
1111
const { internalModuleReadJSON } = internalBinding('fs');
1212
const { toNamespacedPath } = require('path');
13-
const { kEmptyObject } = require('internal/util');
13+
const { kEmptyObject, setOwnProperty } = require('internal/util');
1414

1515
const { fileURLToPath, pathToFileURL } = require('internal/url');
1616

@@ -73,20 +73,14 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
7373
let parsed;
7474
try {
7575
parsed = JSONParse(string);
76-
} catch (error) {
77-
if (isESM) {
78-
throw new ERR_INVALID_PACKAGE_CONFIG(
79-
jsonPath,
80-
(base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
81-
error.message,
82-
);
83-
} else {
84-
// For backward compat, we modify the error returned by JSON.parse rather than creating a new one.
85-
// TODO(aduh95): make it throw ERR_INVALID_PACKAGE_CONFIG in a semver-major with original error as cause
86-
error.message = 'Error parsing ' + jsonPath + ': ' + error.message;
87-
error.path = jsonPath;
88-
throw error;
89-
}
76+
} catch (cause) {
77+
const error = new ERR_INVALID_PACKAGE_CONFIG(
78+
jsonPath,
79+
isESM && (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
80+
cause.message,
81+
);
82+
setOwnProperty(error, 'cause', cause);
83+
throw error;
9084
}
9185

9286
result.exists = true;

test/sequential/test-module-loading.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ assert.throws(
128128

129129
assert.throws(
130130
function() { require('../fixtures/packages/unparseable'); },
131-
/^SyntaxError: Error parsing/
131+
{ code: 'ERR_INVALID_PACKAGE_CONFIG' }
132132
);
133133

134134
{

0 commit comments

Comments
 (0)