从自定义exception类中获取“消息”
这个问题在这里提到答案 。 我需要访问自定义exception的message
。 这可能吗?
我认为直接调用message
就足够了,如下例所示:
class MyCustomError < StandardError attr_reader :object def initialize(object) @object = object puts message end end
但这不是我的预期。 它给了我一些字符串:
"MyModuleNameHere::MyCustomExceptionClassNameHere"
代替:
"a message"
我的直觉倾向于否,因为initialize
构造函数不接受"a message"
文本。
您将错误的类名称作为默认message
因为您没有为message
设置任何内容。 一旦你设置了什么,你就会得到它。
您可以传递消息并调用通常会收到消息的super
消息,例如StandardError.new("oh no")
。
class MyCustomError < StandardError def initialize(message, object) # ... super(message) end end MyCustomError.new("Oh no", thing).message # => "Oh no"
这本关于Rubyexception的电子书非常值得: http : //exceptionalruby.com/