javascript - TypeError:Object.setPrototypeOf 调用 null 或未定义

标签 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';
  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/

相关文章:

javascript - 组织 Docco 页面的更好方法

javascript - 使用node.js async 和 require 获取多个url

python - 类型错误:需要类似字节的对象,不是 'str',但类型是 'bytes'

python-2.7 - 导入 matplotlib.pyplot 时出现 Matplotlib TypeError

javascript - 在 Javascript 中使用警报时出错(对象的属性 'alert' 不是函数)

javascript - 从 span 的 innerHTML 获取 `selectionStart`

javascript - jQuery 抓取输入类型为 ='file' 的上传文件

javascript - 依赖关系问题动态加载 JavaScript

node.js - 如何更改node.js中的ejs模板来避免这种情况

javascript - UpdateCellsRequest - 范围未按预期运行