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

前端 未结 10 1582
-上瘾入骨i
-上瘾入骨i 2020-12-12 12:00

When I get exceptions, it is often from deep within the call stack. When this happens, more often than not, the actual offending line of code is hidden from me:



        
相关标签:
10条回答
  • 2020-12-12 12:40

    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.

    0 讨论(0)
  • 2020-12-12 12:46

    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)

    0 讨论(0)
  • 2020-12-12 12:46

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

    puts caller
    
    0 讨论(0)
  • 2020-12-12 12:46

    Almost everybody answered this. My version of printing any rails exception into logs would be:

    begin
        some_statement
    rescue => e
        puts "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
        Rails.logger.error "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    end
    
    0 讨论(0)
  • 2020-12-12 12:49

    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
    
    0 讨论(0)
  • 2020-12-12 12:50

    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
    
    0 讨论(0)
提交回复
热议问题