【问题标题】:Property in subclass of Error not set未设置错误子类中的属性
【发布时间】:2013-10-18 15:52:58
【问题描述】:

我有一个 Error 的 Coffeescript 子类。以下 CoffeeScript 脚本

class MyError extends Error
  constructor: (message, @cause) ->
    super message

myError = new MyError 'This is the error message!'

console.log myError instanceof MyError
console.log myError instanceof Error
console.log "'#{myError.message}'"
console.log myError.message == ''

展示

true
true
''
true

在 Node.js v0.10.20 下。

为什么myError的message属性是空的?

【问题讨论】:

标签: node.js coffeescript


【解决方案1】:

显式设置@message 有效

class MyError extends Error
  constructor: (@message,@cause)->
    Error.captureStackTrace(@,@)

coffee> ee=new MyError 'test'
{ message: 'test', cause: undefined }
coffee> "#{ee}"
'Error: test'
coffee> ee.message
'test'
coffee> ee instanceof MyError
true
coffee> ee instanceof Error
true
coffee> throw new MyError 'test'
Error: test
    at new MyError (repl:10:11)
...

当另一个类基于MyError 构建时,super 可以正常工作

class OError extends MyError
   constructor: (msg)->
     super msg
     @name='OError'

以下显示正确的消息,对于util.isError 是正确的,是instanceof Error,但不是instanceof Error1。所以它是Error 的专用构造函数,而不是“子类”。

class Error1 extends Error
   constructor: (@message)->
     self = super
     self.name = 'Error1'
     return self

这是给node: '0.10.1', 'coffee-script': '1.6.3'

bjb.io 文章中的最后一个示例是(在 Coffeescript 中):

CustomError = (msg)->
  self = new Error msg
  self.name = 'CustomError'
  self.__proto__ = CustomError.prototype
  return self
CustomError.prototype.__proto__= Error.prototype
# CustomError::__proto__= Error::  # I think

满足所有测试,util.isErrorinstanceof Errorinstanceof CustomError"#{new CustomError 'xxx'}"

【讨论】:

  • 感谢您的详细回答。它证实了我的结论,即在 CS 中子类化 Error 并不会导致满足我所有要求的类:在 Node.js 下正确的 instanceof、正确的属性 util.isError ee == true。读过“An argument against subclassing Error”后,我不再考虑子类化Error
  • 感谢您的补充!我的问题现在得到了完全的回答!据我了解,CustomError 满足所有测试,但不是真正的子类。我检查了class CustomError2 extends CustomError ... 不满足所有测试。
猜你喜欢
  • 2022-10-06
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多