【问题标题】:What are the arguments for the Error constructor function that nodejs uses?nodejs 使用的 Error 构造函数的参数是什么?
【发布时间】:2015-04-08 13:50:37
【问题描述】:

我知道你可以向构造函数传递这样的消息:

err = new Error('This is an error');

但是否还有更多参数可以处理,例如错误名称、错误代码等...?

我也可以这样设置:

err.name = 'missingField';
err.code = 99;

但为了简洁起见,如果构造函数可以接受它们,我想将它们传递给构造函数。

我可以包装函数,但只在需要时才这样做。

构造函数或文档的代码在哪里?我已经搜索了网络、nodejs.org 站点和 github 并没有找到它。

【问题讨论】:

    标签: node.js error-handling


    【解决方案1】:

    您在 node.js 中使用的 Error 类不是特定于节点的类。它来自 JavaScript。

    正如MDN 所述,Error 构造函数的语法如下:

    new Error([message[, fileName[, lineNumber]]])
    

    fileNamelineNumber 不是标准功能。

    要合并自定义属性,您可以手动将其添加到 Error 类的实例中,或者创建自定义错误,如下所示:

    // Create a new object, that prototypally inherits from the Error constructor.
    function MyError(message, code) {
      this.name = 'MyError';
      this.message = message || 'Default Message';
      this.code = code;
    }
    MyError.prototype = Object.create(Error.prototype);
    MyError.prototype.constructor = MyError;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      相关资源
      最近更新 更多