2016-09-26 72 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