【问题标题】:Getting 'message' from a custom exception class从自定义异常类中获取“消息”
【发布时间】:2018-11-03 08:19:00
【问题描述】:

这个问题指的是an answer here。我需要访问自定义异常的message。这可能吗?

我认为直接调用message 就足够了,如本例所示:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object)
    @object = object
    puts message
  end
end

但这不是我所期望的。它给了我一些类似的字符串:

"MyModuleNameHere::MyCustomExceptionClassNameHere"

代替:

"a message"

我的直觉倾向于不,因为initialize 构造函数不接受"a message" 文本。

【问题讨论】:

  • 您真正想对消息做什么?您可能不想在initialize 中打印它。

标签: ruby exception-handling


【解决方案1】:

您可以传递消息并致电super,这通常会接收消息,例如StandardError.new("oh no").

class MyCustomError < StandardError

  def initialize(message, object)
    # ...
    super(message)
  end
end

MyCustomError.new("Oh no", thing).message # => "Oh no"

这本关于 Ruby 异常的电子书非常值得一读:http://exceptionalruby.com/

【讨论】:

    【解决方案2】:

    您将错误的类名作为默认的message,因为您没有为message 设置任何内容。一旦你设置了一些东西,你就会得到它。

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 1970-01-01
      • 2015-11-04
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多