简体   繁体   中英

Debugging Node.js ES Modules: debugger not breaking at uncaught exceptions

I'm running Node.js v19.2.0 and I'm trying to use an Inspector Client to debug my program. I can do it successfully with CommonJS scripts but have issues with ES modules.

I created a very minimal script. It only throws an exception and nothing else:

throw new Error("err");

I saved this both as

  1. test.js (CommonJS script), and
  2. test.mjs (ES module).

Then I tried to run them with a debugger. I tried three: node inspect , Chrome's inspector and VSCode debugger.

  1. With the CommonJS script, the debuggers break when the exception is thrown.

    Chrome 检查器运行 CommonJS 脚本的屏幕截图

  2. With the ES Module, the debuggers doesn't break when the exception is thrown. It breaks instead at node:internal/modules/esm/module_job:194 , executing the line await this.module.evaluate(timeout, breakOnSigint); inside a try-catch statement.

    运行 ES 模块的 Chrome inspector 截图

Does everyone experience the same, or is this a problem with my setup? Is this a known issue?

How can I make the debugger behave the same way with the ES module as it does with the CommonJS script?

It is possible that your debugger is not properly configured to handle exceptions thrown in ES Modules. The behavior you are experiencing may be due to differences in how exceptions are handled in CommonJS and ES Modules. In CommonJS, exceptions are automatically caught and propagated, whereas in ES Modules, exceptions must be explicitly caught using a try-catch block.

To debug your ES Module script using a debugger, you may need to wrap the code that throws the exception in a try-catch block, like this:

try {
    throw new Error("error");
} catch (err) {
    // Handle the error here
}

You can then set a breakpoint on the catch block and use your debugger to inspect the error when it is caught. This should allow your debugger to properly break on the thrown exception in your ES Module script.

Alternatively, you can also configure your debugger to break on all exceptions, regardless of whether they are caught or uncaught. Consult the documentation for your debugger to learn how to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM