如何调试SystemStackError:堆栈级别太深

时间:2015-01-14 05:11:55

标签: ruby-on-rails-4 mongoid

我不知道发生了什么。

发送 show_prizes 请求后。

我得到了预期的结果并且还得到了错误异常

Rails服务器不能再接受请求。

我完全不知道发生了什么

视图

  - @prizes.each do |prize|
    %tr
      %td.center= prize.id
      %td.center
        = prize.name

控制器

class DashboardController < ApplicationController

  def show_prizes
    if params.has_key? :page 
      prizes = Prize.unscoped.sort(_id: 1).to_a.flatten
      @prizes = Kaminari.paginate_array(prizes).page(params[:page]).per(20)
    else
      prizes = Prize.unscoped.sort(_id: 1).to_a.flatten
      @prizes = Kaminari.paginate_array(prizes).page(1).per(20)
    end
  end
end

控制台

Started GET "/dashboard/show_prizes" for ::1 at 2015-01-14 13:06:41 +0800
Processing by DashboardController#show_prizes as HTML
  MOPED: 127.0.0.1:27017 COMMAND      database=admin command={:ismaster=>1} runtime: 1.4210ms
  MOPED: 127.0.0.1:27017 QUERY        database=vivo_lottery_development collection=prizes selector={"$query"=>{}, "$orderby"=>{"_id"=>1}} flags=[] limit=0 skip=0 batch_size=nil fields=nil runtime: 7.0220ms
  MOPED: 127.0.0.1:27017 GET_MORE     database=vivo_lottery_development collection=prizes limit=0 cursor_id=117556587723 runtime: 15.1670ms
  Rendered dashboard/show_prizes.html.haml within layouts/application (6.7ms)
Completed 200 OK in 262ms (Views: 206.9ms)
[2015-01-14 13:06:42] ERROR SystemStackError: stack level too deep
    /.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/object/json.rb:159
[2015-01-14 13:06:42] ERROR SystemStackError: stack level too deep
    /.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/

1 个答案:

答案 0 :(得分:1)

您最好的选择是启用某种低级别的Ruby调用日志记录,例如:

$call_log_enabled = false
$call_log = open('call_log.txt', 'w')

set_trace_func proc { |event, file, line, id, binding, classname|
  if event == 'call' && $call_log_enabled
    $call_log.puts "#{file}:#{line} #{classname}##{id}"
  end
}

然后,只要您需要打开跟踪,只需修改全局变量:

$call_log_enabled = true

此外,如果您突然在Rails应用程序中获取SystemStackError并使用alias_method_chain,那么在开发模式下重新加载类可能会导致此错误。在这种情况下,您可以将逻辑包装在

Rails.application.config.to_prepare do
   ...
end

to_prepare块中的代码不会在每个开发请求上运行。