在 JavaScript 中自定义抛出新的错误消息

Custom throw new Error message in JavaScript

我通过扩展 Error class:

创建了我自己的错误
class MyError extends Error
{
    constructor(message)
    {
        super(message);
        this.name = this.constructor.name;
    }
}

所以代码如下:

throw new MyError('My Message');

将产生以下输出:

throw new MyError('My Message')
^

MyError: My Message <-- OUR MESSAGE
    at Object.<anonymous> (D:\GitHub\error-meta\main.js:1:7)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

我们可以看到 My message 打印在代码行和堆栈跟踪之间。

我应该如何扩展 Error class 以在 标准错误输出之前打印 My message 或其他文本 ?所以它看起来像这样:

My custom error context data!

/* ... standart error output goes here ... */

如果这不可能,如何完全替换标准错误消息? 它甚至来自哪里?

重要说明:我希望它以未处理的 throw 形式显示,而不在 catch 块中打印数据!

我不确定这是否是您要寻找的,但您可以像这样在标准错误之前解决您自己的错误:

class MyError extends Error {
  constructor(message) {   
      console.error(message)
      super(message);
      this.name = this.constructor.name;
  }   
}

查看错误 class

中的 stack 属性
class MyError extends Error{
    constructor(message){
        super('');
        this.name = this.constructor.name;
        this.stack= message +" : "+ this.stack //also you can replace this with anything you want

    }
}

throw new MyError("This is my message");

然后你会得到类似

的东西
This is my message : MyError
    at Object.<anonymous> (/home/runner/GummyAdmirableEvents/index.js:10:7)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

How should I extend Error class to print "My message" or other text before the standard error output?

您可以通过覆盖 stack 属性:

class MyError extends Error {
    name = this.constructor.name;
    stack = 'My custom error context data!\n' + this.stack;
}

但是,我不建议这样做:.stack 不是真正的标准 (yet), may or may not be used by what is actually displaying the error, and you shouldn't mess with the builtin lazy magic getter.

If this is not possible, how to completely replace standard error message? Where it even comes from?

来自nodejs error propagation, which just logs uncaught exceptions before terminating the process. You can override this default behaviour by adding an uncaughtException event handler on process.

但是,对于 CLI 应用程序,您不应该不处理异常。在你的主函数周围用 try/catch 捕获它,然后做任何你想做的自定义错误报告,然后调用 process.exit.