2009-05-22 18 views
0

例子:CommandLine ::應用程序吞噬我的主要異常,如何避免?

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 

當然的格式是沒有必要的,但我更喜歡他們當初要格式化的方式。

回答

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 
+0

這是偉大的,我把它添加到我的Q和格式化了。 – mark 2009-05-23 08:08:48

0

我迄今發現的解決方案:

  1. 變化CommandLine::ApplicationCommandLine::Application_wo_AutoRun
  2. 命名方法main到別的未使用的,比如'開始
  3. 調用靜態方法App.run返回實例然後撥打你的start方法吧

舉例:

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但不協助如何進一步進行。只有來源學習幫助了這裏。

相關問題