views:

40

answers:

3

I need to get a stack trace object in Ruby; not to print it, just to get it to do some recording and dumping for later analysis. Is that possible? How?

A: 

Try error.backtrace:

Returns any backtrace associated with the exception.  
The backtrace is an array of strings, each containing either ``filename:lineNo: in `method’’’ or ``filename:lineNo.’‘

   def a
     raise "boom"
   end

   def b
     a()
   end

   begin
     b()
   rescue => detail
     print detail.backtrace.join("\n")
   end
produces:

   prog.rb:2:in `a'
   prog.rb:6:in `b'
   prog.rb:10
Nikita Rybak
I presume I'll have to throw an exception just to get the stack trace.
J. Pablo Fernández
@J. Pablo Seems so. Post here if you find a way to get it directly.
Nikita Rybak
Sven nailed it with Kernel.caller.
J. Pablo Fernández
fuck you very much, downvoter
Nikita Rybak
A: 

This link explains exception handling mechanism in ruby.

Bragboy
I'm not interested in exceptions, just in getting a stack trace.
J. Pablo Fernández
+3  A: 

You can use Kernel.caller for this. The same method is used when generating stack traces for exceptions.

From the docs:

def a(skip)
  caller(skip)
end
def b(skip)
  a(skip)
end
def c(skip)
  b(skip)
end
c(0)    »   ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
c(1)    »   ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2)    »   ["prog:8:in `c'", "prog:12"]
c(3)    »   ["prog:13"]
Sven Koschnicke