2015-12-28 86 views
1

我想弄清楚在Ruby on Rails中引發特定錯誤和錯誤消息的最佳方法。我的用例是,我偶爾會遇到一個超時錯誤,它隨時會拋出一個常規錯誤,我想在相同的一般錯誤中以不同於其他錯誤的方式處理超時錯誤。我不確定在一般錯誤中可能會拋出哪些其他類型的錯誤,但我認爲更多錯誤存在。我在下面有一些示例代碼來說明我目前正在如何處理它,但是我認爲可能有更好的方法,我還沒有找到?Ruby on Rails錯誤處理,捕獲錯誤和消息

tries = 0 
begin 
    tries += 1 
    <code> 
rescue Foo::Bar => e 
    case e.to_s 
    when 'More specific timeout error message' 
    retry unless tries >= 5 
    else 
    # Let me see other error messages 
    log.info("Error: #{e.to_s}") 
    end 
end 
+0

是否確定使用通用異常類而不是自己的類引發超時,如Timeout :: Error? –

+0

是的,所以這個錯誤來自一個不時超時的外部庫,並且通過超時消息返回外部庫的一般錯誤。 – CarlyL

回答

0

看看retriable gem。這似乎很適合你的建議。通常你會從特定的錯誤類型中解救出來,但是可測試的也可以讓你選擇基於錯誤信息進行救援。

begin 
    Retriable.retriable on: { Foo::Bar => /More specific timeout error message/ }, tries: 3 do 
    # will retry if an error of type Foo::Bar is raised 
    # and its message matches /More specific timeout error message/ 

    # code here... 
    end 
rescue => e # rescue for everything else 
    puts e.message # same as e.to_s 
end 
3

您可以使用多rescue來處理不同的錯誤。

begin 
    # DO SOMETHING 
rescue Net::Timeout => e # change it to the error your want to catch, check the log. 
    # handle it 
rescue SyntaxError => e # just an example 
    # handle it 
rescue => e # any error that not catch by above rescue go here. 
    # handle it 
end 

瞭解更多: http://phrogz.net/programmingruby/tut_exceptions.html

你可以嘗試Rollbar,它幫助生產報告錯誤。