Brad Borch
Brad Borch

Reputation: 319

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.

Upvotes: 1

Views: 1920

Answers (2)

Brozorec
Brozorec

Reputation: 1183

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.

Upvotes: 0

Inpego
Inpego

Reputation: 2667

"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

Upvotes: 2

Related Questions