Getting 'message' from a custom exception class

拈花ヽ惹草 提交于 2019-12-25 01:19:32

问题


This question refers to an answer here. I need to access message of a custom exception. Is this possible?

I thought that directly calling message will suffice as in this example:

class MyCustomError < StandardError
  attr_reader :object

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

but this is not what I expected it to be. It gave me some string like:

"MyModuleNameHere::MyCustomExceptionClassNameHere"

instead of:

"a message"

My intuition is leaning towards no, since the initialize constructor does not take the "a message" text.


回答1:


You get the class name of the error as the default message because you have not set anything for message. Once you set something, you will get it.




回答2:


You can pass the message and call super which will normally take a message, e.g. StandardError.new("oh no").

class MyCustomError < StandardError

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

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

This ebook on Ruby exceptions is well worth it: http://exceptionalruby.com/



来源:https://stackoverflow.com/questions/50503673/getting-message-from-a-custom-exception-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!