我有一个 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;
这曾经工作得很好。我可以抛出 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)
最佳答案
require('util').inherits(module.exports, Error); module.exports = CustomError;
显然module.exports
是一个空对象,第一行有一个undefined
.prototype
。您需要在创建构造函数后调用inherits
!向下移动该行,或使用
require('util').inherits(CustomError, Error);
即使在顶部也能工作,因为函数声明被提升了。
This used to work fine.
不完全是,但它没有抛出错误 before node v6 .
关于javascript - TypeError:Object.setPrototypeOf 调用 null 或未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39099527/