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

发布于 2025-01-16 02:58:10 字数 1305 浏览 3 评论 0原文

我通过扩展 Error 类创建了自己的错误:

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 类以在标准错误输出之前打印 My message 或其他文本?所以它看起来像这样:

My custom error context data!

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

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

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

I have created my own error by extending Error class:

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

So the following code:

throw new MyError('My Message');

will produce the following output:

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

We can see that My message is printed between code line and stack trace.

How should I extend Error class to print My message or other text before the standart error output? So it would look like this:

My custom error context data!

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

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

Important note: I want this to be displayed in unhanlded throw, without printing data in catch block!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

空城旧梦 2025-01-23 02:58:10

我应该如何扩展 Error 类以在标准错误输出之前打印“我的消息”或其他文本?

您也许可以通过覆盖 stack 属性来做到这一点:

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

但是,我不建议这样做:.stack 并不是真正的标准(尚未),可能会也可能不会被 实际显示错误的内容,你不应该搞乱内置的惰性魔法吸气剂

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

它来自 nodejs 错误传播,它只是记录未捕获的日志终止进程之前发生异常。您可以通过添加 uncaughtException 事件处理程序来覆盖此默认行为处理

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

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

You might be able to do this by overwriting the stack property:

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

However, I would not recommend to do this: .stack isn't really standard (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?

It comes from the 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.

However, in the case of a CLI application, you simple shouldn't leave the exception unhandled. Catch it with try/catch around your main function, then do whatever custom error reporting you'd like to do, and call process.exit.

韶华倾负 2025-01-23 02:58:10

查看 Error 类中的 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)

Take a look at the stack attribute from the Error class

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");

You will then get something like

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)
飘逸的'云 2025-01-23 02:58:10

我通常在我的节点项目中使用它来进行自定义错误处理,如下所示

  class ApiError extends Error {
    constructor(
      statusCode,
      message = 'Something Went Wrong!',
      errors = [],
      stack = ''
    ) {
      super(message);
      this.statusCode = statusCode;
      this.data = null;
      this.message = message;
      this.success = false;
      this.errors = errors;

      if (stack) {
        this.stack = stack;
      } else {
        Error.captureStackTrace(this, this.constructor);
      }
    }
  }

  export { ApiError };

I usually use it in my node projects for custom error handling like this

  class ApiError extends Error {
    constructor(
      statusCode,
      message = 'Something Went Wrong!',
      errors = [],
      stack = ''
    ) {
      super(message);
      this.statusCode = statusCode;
      this.data = null;
      this.message = message;
      this.success = false;
      this.errors = errors;

      if (stack) {
        this.stack = stack;
      } else {
        Error.captureStackTrace(this, this.constructor);
      }
    }
  }

  export { ApiError };
牛↙奶布丁 2025-01-23 02:58:10

我不确定这是否是您正在寻找的,但您可以在标准错误之前解决您自己的错误,如下所示:

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

i'm not sure if this is what you are seeking but you can console out your own error before the standart one like this :

class MyError extends Error {
  constructor(message) {   
      console.error(message)
      super(message);
      this.name = this.constructor.name;
  }   
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文