Home > Mobile >  How to show useful error backtrace on nodejs es module?
How to show useful error backtrace on nodejs es module?

Time:09-17

I try to use es module with nodejs, but seems that it's error backtrace dosen't show where the error was thrown?

// copy and rename to `a.cjs` and `a.mjs`
console.log("hi")
throw "err"
node --trace-uncaught a.cjs
node --trace-uncaught a.mjs

CommonJS

[kkocdko@fedora kblog]$ node --trace-uncaught a.cjs
hi

/home/kkocdko/misc/code/kblog/a.cjs:2
throw "err"
^
err
Thrown at:
    at /home/kkocdko/misc/code/kblog/a.cjs:2:1
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:822:12)
    at executeUserEntryPoint (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

ES Module

[kkocdko@fedora kblog]$ node --trace-uncaught a.mjs
hi

node:internal/process/esm_loader:94
    internalBinding('errors').triggerUncaughtException(
                              ^
err
Thrown at:
    at loadESM (node:internal/process/esm_loader:94:31)

The CommonJS version reported the position of error, but ES Module does not. This cause debuging to be difficult. How to show useful error backtrace on nodejs es module?

CodePudding user response:

Throwing an Error populates the stack, throwing a String does not.

throw new Error('err')
$ node a.mjs
file:///so73742023/a.mjs:7
throw new Error('err')
      ^

Error: err
    at file:///so73742023/a.mjs:7:7
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:528:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

Don't throw strings.

CodePudding user response:

Have you tried console.error OR Error.captureStackTrace? If these don't work for you then you could try using the node-stack-trace module, a power full module to track call stacks.

  • Related