Skip to content

module: fix error reporting #55561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
@@ -36,6 +36,7 @@ const {
ArrayPrototypeUnshiftApply,
Boolean,
Error,
ErrorCaptureStackTrace,
JSONParse,
ObjectDefineProperty,
ObjectFreeze,
@@ -1674,6 +1675,7 @@ function getRequireESMError(mod, pkg, content, filename) {
const usesEsm = containsModuleSyntax(content, filename);
const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath,
packageJsonPath);
ErrorCaptureStackTrace(err, Module.prototype.require);
// Attempt to reconstruct the parent require frame.
const parentModule = Module._cache[parentPath];
if (parentModule) {
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import nothing from 'somewhere';
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function main() {
func1(func2(func3()))
}

function func1() {
require('./app.js')
}
function func2() {}
function func3() {}

main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import '../common/index.mjs';
import { test } from 'node:test';
import * as fixtures from '../common/fixtures.mjs';
import { spawnSync } from 'node:child_process';
import assert from 'node:assert';

test('correctly reports error for a longer stack trace', () => {
// The following regex matches the error message that is expected to be thrown
//
// package-type-module/require-esm-error-annotation/index.cjs:6
// require('./app.js')
// ^

const fixture = fixtures.path('es-modules/package-type-module/require-esm-error-annotation/index.cjs');
const args = ['--no-experimental-require-module', fixture];
const regex = /index\.cjs:6[\n\r]+\s{2}require\('\.\/app\.js'\)[\n\r]+\s{2}\^/;

const result = spawnSync(process.execPath, args);
const stderr = result.stderr.toString();

assert.strictEqual(result.status, 1);
assert.strictEqual(result.stdout.toString(), '');
assert.match(stderr, regex);
});