CommandLine :: Application在main中吞下我的异常,如何避免?

时间:2009-05-22 10:58:09

标签: ruby

示例:

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

结果

$ ruby test.rb
ERROR: foo

这里问题就出现了:在开发过程中,我的代码中总会有异常抛出异常,我需要查看堆栈跟踪而不是一些错误的消息。

感谢猖獗,我现在正在使用此解决方案:

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

当然格式化程序不是必需的,但我更喜欢它们最初格式化的方式。

2 个答案:

答案 0 :(得分:1)

或者,你可以拯救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

答案 1 :(得分:0)

到目前为止我找到的解决方案:

  1. CommandLine::Application更改为CommandLine::Application_wo_AutoRun
  2. 将方法main重命名为未使用的其他内容,例如`start
  3. 调用静态方法App.run,它返回实例,然后在其上调用start方法
  4. 完整示例:

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

    documentation提及Application_wo_AutoRun,但没有协助如何进一步处理。只有来源学习在这里有所帮助。

相关问题