Skip to content

Commit

Permalink
module: harmonize error code between ESM and CJS
Browse files Browse the repository at this point in the history
PR-URL: #48606
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Jan Krems <jan.krems@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
  • Loading branch information
aduh95 authored Jul 4, 2023
1 parent 586fcff commit 3ce51ae
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 16 deletions.
24 changes: 9 additions & 15 deletions lib/internal/modules/package_json_reader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion test/sequential/test-module-loading.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ assert.throws(

assert.throws(
function() { require('../fixtures/packages/unparseable'); },
/^SyntaxError: Error parsing/
{ code: 'ERR_INVALID_PACKAGE_CONFIG' }
);

{
Expand Down

0 comments on commit 3ce51ae

Please sign in to comment.