我有Java开发人员的背景,并且对JavaScript / TypeScript很陌生。
是否有标准方法来管理和保持JavaScript / TypeScript错误的原因?
我的目的是在将错误包装到另一个错误中时获得完整的堆栈跟踪信息;有点像Java异常stacktrace:
Message of exception 1
...
Caused by: Message of exception 2
...
Caused by: Message of the root exception
我尝试此代码,但err1
不保留err2
的引用:
// CODE
try {
try {
throw new Error("Error no2");
} catch (err2) {
console.log("========================================");
console.log(err2);
throw new Error("Error no1");
}
} catch (err1) {
console.log("========================================");
console.log(err1);
}
// CONSOLE OUTPUT
$ node test.ts
========================================
Error: Error no2
at Object.<anonymous> (/tmp/test.ts:3:15)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
========================================
Error: Error no1
at Object.<anonymous> (/tmp/test.ts:7:15)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
此外,我没有在Error类中找到任何名为cause
的属性。有stack
属性,但我认为更改此属性是一个不好的做法。
谢谢!
我一直使用Kristian's answer here的修改
class TraceableError extends Error {
trace: Error;
constructor(message?: string, innerError?: Error) {
super(message);
this.trace = innerError;
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); }
else { this.__proto__ = actualProto; }
}
}
然后您将像这样抛出
try {
try {
throw new Error("Error no2");
} catch (err2) {
console.log("========================================");
console.log(err2);
throw new TraceableError ("Error no1", err2);
}
} catch (err1) {
console.log("========================================");
console.log(err1);
}
注意,如果未捕获,则新错误的
trace
部分将不会输出到控制台。