【问题标题】:TypeError: Object.setPrototypeOf called on null or undefinedTypeError: Object.setPrototypeOf 在 null 或 undefined 上调用
【发布时间】:2017-02-21 12:02:44
【问题描述】:

我有一个 Node.js 项目,其中有我自己的自定义错误:

'use strict';

require('util').inherits(module.exports, Error);

function CustomError(message, extra) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.type = 'CustomError';
  this.message = message;
  this.extra = extra;
};

module.exports = CustomError;

这曾经工作得很好。我可以Throw new CustomError('my message', dataObject) 并独立于提供错误类型捕获该错误并相应地控制程序流。

但是,自从将 Node 更新到最新的稳定版本 (v6.4.0) 后,它现在已损坏。当我运行我的单元测试时,我得到了错误:

TypeError: Object.setPrototypeOf called on null or undefined
    at Function.setPrototypeOf (native)
    at Object.exports.inherits (util.js:973:10)
    at Object.<anonymous> (CustomError.js:3:17)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)

【问题讨论】:

    标签: javascript node.js typeerror


    【解决方案1】:
    require('util').inherits(module.exports, Error);
    module.exports = CustomError;
    

    显然module.exports 是一个空对象,第一行有一个undefined .prototype。您需要在创建构造函数之后调用inherits!向下移动该行,或使用

    require('util').inherits(CustomError, Error);
    

    即使在顶部也可以工作,因为函数声明被提升了。

    这曾经工作得很好。

    不完全是,但它没有抛出错误before node v6

    【讨论】:

    • module.exports === exports === {},默认不是undefined
    • @mscdex 正确,已修复。 setPrototypeOf 不会直接调用它
    • 这似乎真的很明显,现在它向我指出了!我仍然对它如何工作感到有些困惑。我开始怀疑代码是否发生了变化,但 git history 却相反,它目前正在使用旧版本的 Node.js 在生产环境中运行。
    【解决方案2】:

    看到我正在升级 Node 以尝试一些 ES6 细节,我想我会重构以以更现代的方式扩展该类:

    'use strict';
    
    module.exports = class CustomError extends Error{
        constructor (message, extra){
              super(message);
              this.name = this.constructor.name;
              this.type = 'CustomError';
              this.extra = extra;
        }
    }
    

    我认为这是一个更好的长期解决方案,尽管 @Bergi 似乎已经回答了所提出的问题。

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 2021-12-07
      • 2022-10-24
      • 2023-01-20
      • 2022-06-16
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      相关资源
      最近更新 更多