JP.
JP.

Reputation: 5594

Ruby's Exception Error classes

You can create a subclass of an exception to make it more descriptive, but how should you set the default 'message'?

class MyError < StandardError
  # default message = "You've triggered a MyError"
end

begin
  raise MyError, "A custom message"
rescue Exception => e
  p e.message
end

begin
  raise MyError
raise Exception => e
  p e.message
end

The first should output 'A custom message'

The second should output 'You've triggered a MyError'

Any suggestions as to best practice?

Upvotes: 34

Views: 19142

Answers (2)

Andrew Vilcsak
Andrew Vilcsak

Reputation: 3429

You may also overwrite the message method in your subclass and return the string you'd like displayed. I prefer this as it seems to keep things a little cleaner if you want to do anything interesting before displaying the message.

class CustomError < StandardError

  def initialize(error_code, error_info)
    @code, @info = error_code, error_info
  end

  def message
    "<Code: #{@code}> <Info: #{@info}>"
  end

end

Upvotes: 3

sepp2k
sepp2k

Reputation: 370212

Define an initialize method, which takes the message as an argument with a default value. Then call StandardError's initialize method with that message (using super).

class MyError < StandardError
  def initialize(msg = "You've triggered a MyError")
    super(msg)
  end
end

Upvotes: 66

Related Questions