I found myself using exception object (instead of ) more and more. They
are convenient for storing detailed information bits about the error
(pointer to an object structure/within an object structure, some flags,
etc).
Since RCR 21[1] (New method: Exception#message=) was rejected, can
anyone suggest a more elegant way of doing the thing below. I don’t like
having to set the message everytime. The message will be the same most
of the time anyway, since more detailed information can be found in the
attributes of the exception object. So I’d like to store the message in
the exception object “template” and change them occassionally when needed.
class SomeError < StandardError
attr_accessor :foo, :bar, :baz
def initialize(foo, bar, baz) @foo = foo @bar = bar @baz = baz
end
end
I found myself using exception object (instead of ) more and more. They
are convenient for storing detailed information bits about the error
(pointer to an object structure/within an object structure, some flags,
etc).
Since RCR 21[1] (New method: Exception#message=) was rejected, can
anyone suggest a more elegant way of doing the thing below. I don’t like
having to set the message everytime. The message will be the same most
of the time anyway, since more detailed information can be found in the
attributes of the exception object. So I’d like to store the message in
the exception object “template” and change them occassionally when
needed.
This is not difficult:
class MyException < Exception
attr_accessor :msg
def initialize(msg = “Default”) @msg = msg
super
end
def exception
self.class.new msg
end
end
e = MyException.new
begin
puts “foo”
raise e
rescue MyException => e
p e
end
begin
puts “foo”
e.msg = “another error”
raise e
rescue MyException => e
p e
end
Although I’d prefer to have a default message at class level:
class MyException < Exception
class <<self
attr_accessor :msg
end
self.msg = “Default”
def initialize(msg = self.class.msg)
super(msg)
end
end
e = MyException.new
begin
puts “foo”
raise e
rescue MyException => e
p e
end
begin
puts “foo”
MyException.msg = “another error”
raise MyException
rescue MyException => e
p e
end