module: harmonize error code between ESM and CJS

PR-URL: https://github.com/nodejs/node/pull/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>
pull/48652/head
Antoine du Hamel 2023-07-04 11:52:56 +02:00 committed by GitHub
parent 586fcff061
commit 3ce51ae9c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 16 deletions

View File

@ -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;

View File

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