简体   繁体   中英

accessing variables in rescue_from block

So I have a fairly common rescue_from block in a Rails app:

  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

but I want to be able to see the error message if I'm an admin user, so I change the "unless" line to:

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

but rails complains: "undefined local variable or method `current_user' for ApplicationController:Class"

So how can I access the instance variables, since the code isn't within a block?

I also tried to wrap it in the before_filter block:

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

end

but the app wouldn't run on the server.

"rescue_from" is class-level method and doesn't have access to the instance variables. However, you can access them from a method that is called in with:

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

If you haven't found a solution yet, you can try this trick:

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

I agree this approach has some minuses but it worths trying when other possibilities are exhausted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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