【问题标题】:Enable stack dump on exception in Rails console在 Rails 控制台中启用异常堆栈转储
【发布时间】:2013-07-13 08:46:59
【问题描述】:

我正在使用带有 pry gem 的 Ruby on Rails。当 rake 任务期间发生错误时,我会得到一个非常好的堆栈跟踪。

但是,当我在 Rails 控制台中执行触发异常的操作时,我只能看到错误消息和触发它的一行代码(大部分时间在 Rails 核心中的某个位置)。

有没有办法在控制台中启用这些堆栈转储?

【问题讨论】:

    标签: ruby stack-trace rails-console pry


    【解决方案1】:

    我自己找到了解决方案。

    显然,我需要 pry 附带的命令wtf?

    [7] project »  p.known_attributes
    NoMethodError: undefined method `foo' for #<Bar:0x007f871fd12a38>
    from /[...]/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb:436:in `method_missing'
    
    [8] project »  wtf?
    Exception: NoMethodError: undefined method `foo' for #<Bar:0x007f871fd12a38>
    --
    [... stack dump ...]  
    
    [9] project »  
    

    【讨论】:

    • 这让我很开心
    【解决方案2】:

    当控制台出现错误时,您应该会看到类似这样的内容

    $ rails c
    Loading development environment (Rails 4.0.0)
    irb(main):001:0> no_method
    NameError: undefined local variable or method `no_method' for main:Object
        from (irb):1
        from /Users/michal/Projects/tennisliga/.gems/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
        from /Users/michal/Projects/tennisliga/.gems/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
        from /Users/michal/Projects/tennisliga/.gems/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'
    

    它有什么问题?你没有看到堆栈跟踪?

    编辑: 如果您正在使用 pry 并希望查看更多堆栈跟踪,请参阅 pry wiki 简短示例(显示所有行)

    Pry.config.exception_handler = proc do |output, exception, _pry_|
      output.puts "#{exception}"
      output.puts "#{exception.backtrace}"
    end
    

    【讨论】:

    • 当我这样做时,我得到的只是NameError: undefined local variable or method 'no_method' for main:Object from (pry):1:in '&lt;main&gt;'。没有堆栈转储。
    • 我现在才看到 pry 可能参与其中。这可能吗?
    • 您是否将 pry 设置为默认控制台?
    • 是的,如果我运行rails c,我就会被撬开。
    • 谢谢!我自己进行了一些挖掘,结果发现最新的异常在_ex_ 变量中引发后可用,因此您可以使用_ex_.pry 打开它,或者将堆栈转储到_ex_.backtrace。我只是喜欢wtf? 命令,它给了我我需要知道的东西而没有开销。
    猜你喜欢
    • 1970-01-01
    • 2022-12-23
    • 2016-01-11
    • 2016-03-10
    • 2013-09-21
    • 2011-12-27
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多