Enable stack dump on exception in Rails console

核能气质少年 提交于 2020-01-23 05:00:18

问题


I am using Ruby on Rails with the pry gem. When an error occurs during a rake task, I get a very nice stack trace.

When however I do something in my rails console that triggers an exception, I only get to see the error message and the one line of code that triggered it (which most of the time is somewhere in the rails core).

Is there a way to enable these stack dumps in the console?


回答1:


I found a solution myself.

Apparently, I was in need of the command wtf? that comes with pry.

[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:


When there's an error in console you should see something like this

$ 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>'

What's the problem with it? You don't see the stack trace?

EDIT: If you're using pry and would like to see more stack trace, refer to pry wiki Short example (show all lines)

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


来源:https://stackoverflow.com/questions/17655061/enable-stack-dump-on-exception-in-rails-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!