Catching line numbers in ruby exceptions

后端 未结 5 547
孤独总比滥情好
孤独总比滥情好 2021-01-30 16:21

Consider the following ruby code

test.rb:

begin

  puts
  thisFunctionDoesNotExist
  x = 1+1
rescue Exception => e
  p e
end

For deb

5条回答
  •  [愿得一人]
    2021-01-30 17:08

    You can access the backtrace from an Exception object. To see the entire backtrace:

    p e.backtrace
    

    It will contain an array of files and line numbers for the call stack. For a simple script like the one in your question, it would just contain one line.

    ["/Users/dan/Desktop/x.rb:4"]
    

    If you want the line number, you can examine the first line of the backtrace, and extract the value after the colon.

    p e.backtrace[0].split(":").last
    

提交回复
热议问题