扩展错误es6类模块问题

Extending Error es6 class module issue

本文关键字:模块 问题 es6 错误 扩展      更新时间:2023-09-26

我遇到了一个非常奇怪的错误。我正在试着调试为什么我不能用babel 6处理这个模块es6错误。测试不断失败。其中一个测试相当简单——自定义错误的实例应该是错误。这两者都应该是true

console.log(err instanceof Error)
console.log(err instanceof ExtendableError)

以下是jsbin上完全相同的src代码的示例,其中两个日志都返回true

  • 带有未编译工作babel代码的jsbin
  • jsbin与已编译的工作babel代码

如果您将代码放入一个节点文件并运行它,也会发生同样的行为

很明显,测试失败的原因是模块导入工作不正常,这很奇怪地失败了。

import ExtendableError from './index'
var b = new ExtendableError();
console.log(b instanceof ExtendableError) // false
console.log(b instanceof Error) // true

为什么当ExtendableError的声明与console.log在同一个文件中时,我会得到truetrue的有效行为,而当我在它自己的文件中有ExtendableError时,它会变成falsetrue

这是babel 5代码的输出。

浏览了babel slack频道,并迅速了解了允许与babel 5向后兼容的插件。

https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend

{
  ["babel-plugin-transform-builtin-extend", {
    "globals": ["Error"],
    "approximate": true
  }]
}

这是pr到es6的错误。

解决方法是停止使用Babel的polyfill for extends,并在您自己的上进行扩展

class ExtendableError {
  constructor(message = '') {
    Error.call(this, message)
    // extending Error is weird and does not propagate `message`
    Object.defineProperty(this, 'message', {
      enumerable : false,
      value : message,
      writable : true,
    });
    Object.defineProperty(this, 'name', {
      enumerable : false,
      value : this.constructor.name,
      writable : true,
    });
    if (Error.hasOwnProperty('captureStackTrace')) {
      Error.captureStackTrace(self, this.constructor);
      return
    }
    Object.defineProperty(this, 'stack', {
      enumerable : false,
      value : (new Error(message)).stack,
      writable : true,
    });
  }
}
ExtendableError.prototype = Object.create(Error.prototype)
var b = new ExtendableError()
console.log(b instanceof Error) // true
console.log(b instanceof ExtendableError) // true