2015-11-04 94 views
1

所以我有一个Rails应用程序一个相当普遍的rescue_from块:变量的访问

if Rails.env.production? 
    unless Rails.application.config.consider_all_requests_local 
     rescue_from Exception, with: lambda { |exception| render_error 500, exception } 
     rescue_from Mongoid::Errors::DocumentNotFound, with: lambda { |exception| render_error 404, exception } 
    end 
    end 

,但我希望能够看到错误消息,如果我是一个管理员用户,所以我改变在“除非”行:

unless Rails.application.config.consider_all_requests_local || (current_user.present? && current_user.site_amdin) 

但轨道抱怨:“未定义的局部变量或方法`CURRENT_USER”的ApplicationController中:类”

所以,我怎么能访问实例变量,罪代码不在一个块内?

我也试图把它包在的before_filter块:

before_filter do 
if Rails.env.production? || (current_user.present? && current_user.site_admin) 
    unless Rails.application.config.consider_all_requests_local 
     Application.rescue_from Exception, with: lambda { |exception| render_error 500, exception } 
     Application.rescue_from Mongoid::Errors::DocumentNotFound, with: lambda { |exception| render_error 404, exception } 
    end 
end 

但应用程序不会在服务器上运行。

回答

1

“rescue_from”是类级方法,无法访问实例变量。

if Rails.env.production? 
    unless Rails.application.config.consider_all_requests_local 
    rescue_from Exception, with: :show_exception 
    rescue_from Mongoid::Errors::DocumentNotFound, with: lambda { |exception| render_error 404, exception } 
    end 
end 

# at the end of file 

protected 

def show_exception(exception) 
    if current_user.present? && current_user.site_admin 
    render text: ([exception.message] + exception.backtrace).join('<br />') # render error for admin 
    else 
    render_error 500, exception 
    end 
end 
+0

当然,但是通过这样做,我绕过了当我不求助于rescue_from时得到的本机错误报告。但我想我可以通过在模板中输出错误消息来复制该格式。 –

+0

为此尝试“引发异常”。 – Inpego

0

如果你暂时还没有发现一个解决方案,你可以试试这招:

unless Rails.application.config.consider_all_requests_local || (Thread.current[:user].present? && Thread.current[:user].site_amdin) 

我同意这种做法有但是,你可以从一个被称为与方法访问它们有些缺点,但在其他可能性耗尽时值得尝试。