问题
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