[英]How to show useful error backtrace on nodejs es module?
I try to use es module with nodejs, but seems that it's error backtrace dosen't show where the error was thrown?我尝试将 es 模块与 nodejs 一起使用,但似乎它的错误回溯并没有显示错误发生的位置?
// copy and rename to `a.cjs` and `a.mjs`
console.log("hi")
throw "err"
node --trace-uncaught a.cjs
node --trace-uncaught a.mjs
[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
[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. CommonJS版本报错position,而ES Module没有。 This cause debuging to be difficult.这导致调试很困难。 How to show useful error backtrace on nodejs es module?如何在 nodejs es 模块上显示有用的错误回溯?
Throwing an Error
populates the stack, throwing a String
does not.抛出一个Error
会填充堆栈,抛出一个String
不会。
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.不要扔字符串。
Have you tried console.error
OR Error.captureStackTrace
?您是否尝试过console.error
或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.如果这些对您不起作用,那么您可以尝试使用node-stack-trace模块,这是一个强大的模块来跟踪调用堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.