Skip to content

Unable to catch error thrown during require in node.js v22 (works in v20) #56115

Description

@davidfirst

Version

v22.11.0

Platform

Darwin Davids-MacBook-Pro.local 23.6.0 Darwin Kernel Version 23.6.0: Mon Jul 29 21:14:30 PDT 2024; root:xnu-10063.141.2~1/RELEASE_ARM64_T6000 arm64

Subsystem

No response

What steps will reproduce the bug?

Create a new directory and add two files: bar.js and foo.js.

bar.js

try {
  require('./foo');
} catch (err) {
  console.log('got an error', err);
}

foo.js

Object.defineProperty(exports, "__esModule", { value: true });
const module_1 = require("module");
const require = (0, module_1.createRequire)(import.meta.url);

Run node bar.js.

Observe that with node v22 it exits with code 1 while with node v20 it exits with code 0.

How often does it reproduce? Is there a required condition?

It reproduces constantly.

What is the expected behavior? Why is that the expected behavior?

I expect node to exit with code 0 because I wrapped the require with try/catch.

What do you see instead?

node exits with code 1.

Additional information

In practice, bar.js is my CLI tool, and foo.js is a user-created plugin over which I have no control.

Activity

  1. joyeecheung commented on Dec 3, 2024

    @joyeecheung
    Member

    It seems in this case the module being loaded by require() is recognized as ESM (due to the presence of const require) by syntax detection and went into require(esm), which is kind of odd because require(esm) is still behind a flag in 22.11.0, it might be another glitch from the syntax detection unflagging.

    But anyway, it makes the process exit because the evaluation promise is created by V8 and once rejection happens it goes straight into the unhandled rejection handler, so we need to do some fixup later to remove it from the pending unhandled rejections.

  2. joyeecheung commented on Dec 3, 2024

    @joyeecheung
    Member

    Fix in #56122 (there is a separate bug in which require(esm) is not disabled if the module syntax detection indicates the module is ESM, but considering this has been happening on v22.x for quite a while, it is probably not too urgent to fix it).

  3. added
    confirmed-bugIssues and PRs for confirmed bugs.
    moduleIssues and PRs related to the module subsystem.
    on Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugIssues and PRs for confirmed bugs.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions