0

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
CyberMew
  • 1,159
  • 1
  • 16
  • 33
  • What do you actually want to do with the message? You probably don't want to print it within `initialize`. – Stefan May 24 '18 at 08:38

2 Answers2

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
1

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/

Kris
  • 19,188
  • 9
  • 91
  • 111