JavaScript / TypeScript:保持错误原因的标准方法

问题描述 投票:2回答:1

我有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属性,但我认为更改此属性是一个不好的做法。

谢谢!

javascript typescript error-handling stack-trace
1个回答
0
投票

我一直使用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部分将不会输出到控制台。

© www.soinside.com 2019 - 2024. All rights reserved.