检查时未显示 Ruby 异常对象中的自定义字段

Custom fields in a Ruby exception object not shown when inspecting

如果我在Ruby中创建一个class,我通常可以在使用inspect时"see"它的字段:

>> class C; def initialize; @x=1; end; end
=> :initialize
>> C.new.inspect
=> "#<C:0x007fd5b9119c20 @x=1>"

这似乎不适用于例外情况:

>> class E < StandardError; def initialize; super("hello"); @y=2; end; end
=> :initialize
>> begin; raise E.new; rescue E => e; puts e.inspect; end 
#<E: hello>
=> nil

我本以为会显示 #<E: hello @y=2>!所以很自然地我去了 the documentation 并看到 Error class 专门覆盖 inspect 到 "return this exception’s class name and message."

这让我相信要么 (1) 向错误对象添加额外的描述性字段是一件坏事,要么 (2) Ruby Error class 犯了一个错误,或者 (3) 错误对象本身有些奇怪,需要显式覆盖 inspect

我并不是说这是一个意见问题。我这里的编程问题是:

If the answer is (2), how does one get around this mess? Override inspect in one's custom error subclass?

我不知道你为什么要让实例变量出错class,但是如果

how does one get around this mess?

表示

where are the instance variables I have defined for the object?

答案如下:

begin; raise E.new; rescue E => e; puts e.instance_variables; end
#=> @y

要在 inspect 中显示实例变量,您肯定必须重写 inspect 方法:

class E < StandardError
  def initialize
    super('hello')
    @y = 2
  end

  def inspect
    "<#{self.class}: #{message}, #{instance_variables.map { |v| "#{v}=#{instance_variable_get(v)}"}.join(', ')}>"
  end
end
begin; raise E.new; rescue E => e; puts e.inspect; end
#=> <E: hello, @y=2>

我没有看到这里有任何混乱:)