繁体   English   中英

访问result_from块中的变量

[英]accessing variables in rescue_from block

所以我在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)

但是Rails抱怨:“ ApplicationController:Class的未定义局部变量或方法“ current_user””

那么由于代码不在块内,我该如何访问实例变量?

我还尝试将其包装在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

结束

但该应用程序无法在服务器上运行。

“ 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

如果尚未找到解决方案,可以尝试以下技巧:

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

我同意这种方法有一些缺点,但是当其他可能性用尽时,值得尝试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM