2016-09-26 67 views
0

我們在我們的應用程序中使用了raven-sentry,並且我希望對所有錯誤應用默認的「全部捕獲」額外選項。Rails異常 - 從控制器獲取實例變量

class StandardError 
    def raven_context 
    extra = {} 

    #add conditional key/values to the hash if they exist 
    extra[:account_id] = @account.id if @account 

    extra.empty? ? {} : { extra: extra } 
    end 
end 

因爲異常是從在任何一個模型或控制器的實例化的類提高,我想我能夠訪問這些變量。如果accounts#show引發異常,我想要訪問@account。如果Account.create()引發異常,我希望能夠獲取有關該帳戶的一些信息,如錯誤。

這可能嗎?如果是這樣,怎麼樣?

回答

0

您可以按照如何捕捉/拋出異常,如ActiveRecord::RecordInvalid

所以基本上你可以設計一個通用的錯誤,如Rails idea:所以現在

class MyGenericError < StandardError 
    attr_reader :account, :others 

    def initialize(message = nil, account = nil, others={}) 
    @account = account 
    @others = others 
    super(message) 
    end 
end 

class MySpecificError < MyGenericError; end 

當你拋出一個錯誤,只是通過必要的PARAMS,如:

raise MySpecificError.new('doing something wrong', @account) if doing_something_wrong 

最後,捕捉錯誤的時候,你只得到了account attribu te和自由使用它

+0

這裏唯一的問題是它會是我特別提出的錯誤。通過Sentry,我可以通過Raven.capture_exception(e,extra:{whatever我想要的))傳遞所有信息。 Sentry還捕獲未處理的異常,這些是我特別感興趣的。 – TIMBERings