Submitted by Paul Brannan (Thu Dec 18 10:12:30 UTC 2003)
Currently the only way to print exceptions in this format is like this: <pre> str = '' first = true $!.backtrace.each do |bt| str << (first ? "#{bt}: #{exc.message} (#{exc.class}) " : " from #{bt} ") first = false end puts str </pre> (which is similar to what irb does), or via tricks/hacks using threads or fork(). There should be a simple interface to this feature.
<ol> <li>A new C function should be added which either returns a String containing the formatted exception message or prints the formatted exception message to stderr, depending on a flag that is passed to the function. This function can be called error_format().</li> <li>error_print() should be rewritten to call error_format(). It should always tell error_format() to print to stderr, because it is unwise to create objects in the presence of certain exceptions (e.g. MemoryError).</li> <li>The Exception class should get a new function called Exception#format() which formats the exception using error_format() and returns the result as a String.</li> <li>IRB should be changed to use Exception#format() to print exceptions instead of iterating over the backtrace.</li> </ol> For example: <pre> def foo raise 'foo!' end begin foo rescue puts $!.format #=> test.rb:10:in `foo': foo! (RuntimeError) # from test.rb:14 end </pre>
class Exception def format str = '' first = true self.backtrace.each do |bt| str << (first ? "#{bt}: #{self.message} (#{self.class})" : " from #{bt}") first = false end return str end
end
Comments | Current voting | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .
I've got a few "def print_exception" in the scripts I've written. Definitely useful. -matt