From: Leslie Viljoen Date: 2010-04-07T06:58:10+09:00 Subject: Re: Custom Exceptions --000325557b2257e6a60483988a66 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Apr 6, 2010 at 5:24 PM, Brian Candler wrote: > Judging by the C source, Exception uses hidden(*) instance variables > "mesg" and "bt" for message and backtrace respectively. However, the > accessor #message internally calls #to_s, which you can override. > > class BillRowError < StandardError > def initialize(field, index) > @field = field > @index = index > end > > alias :orig_to_s :to_s > def to_s > "#{orig_to_s} field: #{@field}, row: #{@index}" > end > end > > begin > raise BillRowError.new(5, 7), "bar" > rescue BillRowError => e > p e > p e.instance_variables > p e.message > p e.backtrace > end > > Produces: > > # > ["@index", "@field"] > "bar field: 5, row: 7" > ["ert.rb:14"] > > Admittedly this behaviour doesn't seem to be well documented, so may be > fragile. Use at your own risk. > > Wow thanks for this, I didn't think of aliasing the old to_s. I find it strange that exceptions don't just use a plain old @message instance variable but I suppose there's some good reason for it. -- Do not support Microsoft: http://www.vanwensveen.nl/rants/microsoft/IhateMS.html --000325557b2257e6a60483988a66--