tags:

views:

51

answers:

2

Example:

require 'commandline'
class App < CommandLine::Application
    def initialize
    end
    def main
        raise 'foo'
    end
end

results in

$ ruby test.rb
ERROR: foo

And here the problem starts: during development there will always be Exceptions thrown deep somewhere in my code and I need to see the stacktrace and not some mangled message.

Thanks to rampion, I'm now using this solution:

require 'commandline'
class App < CommandLine::Application
    def initialize
    end
    def main
        raise 'foo'
        rescue Exception => e
            puts format_like_real_exception e
    end
    def format_like_real_exception(e)
        s = ''
        b = e.backtrace
        s << b.shift << ': ' << e.message << "\n"
        b.each { |l| s << "\t" << l << "\n" }
        s
    end
end

Of course the formatter is not necessary, but I prefer it the way they're originally formatted.

A: 

The solution I found so far:

  1. Change CommandLine::Application to CommandLine::Application_wo_AutoRun
  2. rename method main to something else which isn't used, e.g `start
  3. call static method App.run which returns the instance and then call your start method on it

Full example:

require 'commandline'
class App < CommandLine::Application_wo_AutoRun
    def initialize
    end
    def start
        raise 'foo'
    end
end
app = App.run
app.start

The documentation mentions Application_wo_AutoRun but doesn't assist how to proceed further. Only source studying helped here.

mark
+1  A: 

Alternately, you could just rescue the errors in main:

require 'rubygems'
require 'commandline'
class App < CommandLine::Application
    def initialize
    end
    def main
        raise 'foo'
    rescue Exception => e
        puts "BACKTRACE:"
        puts e.backtrace
    end
end
rampion
That's great, I added it to my Q and a formatter too.
mark