exception - How do I get ruby to print a full backtrace instead of a truncated one?

ID : 20051

viewed : 22

Tags : rubyexceptionstack-traceruby

Top 5 Answer for exception - How do I get ruby to print a full backtrace instead of a truncated one?

vote vote

90

Exception#backtrace has the entire stack in it:

def do_division_by_zero; 5 / 0; end begin   do_division_by_zero rescue => exception   puts exception.backtrace   raise # always reraise end 

(Inspired by Peter Cooper's Ruby Inside blog)

vote vote

85

You could also do this if you'd like a simple one-liner:

puts caller 
vote vote

70

This produces the error description and nice clean, indented stacktrace:

begin                 # Some exception throwing code rescue => e   puts "Error during processing: #{$!}"   puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}" end 
vote vote

61

IRB has a setting for this awful "feature", which you can customize.

Create a file called ~/.irbrc that includes the following line:

IRB.conf[:BACK_TRACE_LIMIT] = 100 

This will allow you to see 100 stack frames in irb, at least. I haven't been able to find an equivalent setting for the non-interactive runtime.

Detailed information about IRB customization can be found in the Pickaxe book.

vote vote

55

One liner for callstack:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end 

One liner for callstack without all the gems's:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end 

One liner for callstack without all the gems's and relative to current directory

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end 

Top 3 video Explaining exception - How do I get ruby to print a full backtrace instead of a truncated one?

Related QUESTION?