Javascript TypeError:Object.setPrototypeOf调用为null或未定义

Javascript TypeError:Object.setPrototypeOf调用为null或未定义,javascript,node.js,typeerror,Javascript,Node.js,Typeerror,我有一个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';

我有一个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;
这过去很管用。我可以
抛出新的CustomError('my message',dataObject)
并独立于提供的错误类型捕获该错误,并相应地控制程序流

然而,自从将节点更新到最新的稳定版本(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)
TypeError:Object.setPrototypeOf调用为null或未定义
在Function.setPrototypeOf处(本机)
在Object.exports.inherits(util.js:973:10)
反对。(CustomError.js:3:17)
在模块处编译(Module.js:556:32)
在Object.Module._extensions..js(Module.js:565:10)
在Module.load(Module.js:473:32)
在TryModule加载时(module.js:432:12)
在Function.Module.\u加载(Module.js:424:3)
at Module.require(Module.js:483:17)
根据需要(内部/module.js:20:19)
显然,
模块.exports
是一个空对象,第一行有一个
未定义的
.prototype
。创建构造函数后,需要调用
inherits
!向下移动管线,或使用

require('util').inherits(CustomError, Error);
即使在顶部也会起作用,因为函数声明已挂起

这过去很管用


不完全正确,但它没有抛出错误。

鉴于我正在升级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似乎已经回答了问题。

module.exports====exports==={}
,默认情况下它不是未定义的。@mscdex right,已修复
setPrototypeOf
并没有直接调用它,这看起来很明显,现在它被指给我看了!我仍然有点困惑它是如何工作的。我开始怀疑代码是否发生了更改,但git历史记录表明情况并非如此,并且它目前正在生产中使用较旧版本的Node运行。
'use strict';

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