2014-05-09 108 views
0

我有一個使用ActiveRecord但不是Rails的紅寶石應用程序。Activerecord救援

我想拯救所有數據庫錯誤,在我的情況下可以包括SQLite3::BusyException

有沒有更好的辦法比挽救每一個Model.find,Model.where, obj.save等救援?

我想添加一個模塊,每一個猴子補丁/劫持DB動作,如模式,但where出現複雜的東西也不是好惹的:

def where 
    super 
rescue ActiveRecord::RecordNotFound 
rescue SQLite3::BusyException => e 
    p [:warning, e.message] 
end 

回答

0

當使用賽璐珞我遇到類似的問題在那裏我需要捕捉錯誤,因爲連接池無法正確使用Ce​​lluloid使用光纖的方式。我使用類似下面的包裝方法來幫助確保錯誤被​​困住並解決了我的代碼中的連接。對於您的情況,它可能是這樣的:

module TrackActiveRecordErrors 
    def db(&block) 
    begin 
     yield block 
    rescue StandardError => e 
     p [:warning, e.message] 
     # ... and other sort of logging, alerting you'd like 
     raise e 
    ensure 
     # Put your clean-up code here 
    end 
    end 
end 

在班要使用此包裝:

class DoSomething 
    include TrackActiveRecordErrors 

    def find_something(id) 
    db do 
     a_something = Model.find(id) 
    end 
    a_something 
    end 
end 

它不漂亮,但它不是試圖調整AR的魔術在容易得多模型類。

+0

謝謝,但這與猴子直接修補功能非常相似。它帶有類似的「陷阱」。 – nitsujri