Forum: Ruby How can I access after an exception (in the rescue area) the file, class, method, line number for wh

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Greg H. (Guest)
on 2009-01-11 10:33
(Received via mailing list)
Hi,
How can I access after an exception (in the rescue area) the following
information do you know (i.e. associated with where the error occured)?

- file,
- line number
- class
- method

thanks
Radosław B. (Guest)
on 2009-01-11 13:30
(Received via mailing list)
When you catch, err, rescue exception look at the 'backtrace' method.
It won't give you all information you need, but some of them.

# file exc.rb
class A
  def foo
    raise "bar"
  end
end

begin
  a = A.new
  a.foo
rescue => e
  puts e.backtrace
end

$ ruby exc.rb
exc.rb:3:in `foo'
exc.rb:9


--
Pozdrawiam

Rados³aw Bu³at
http://radarek.jogger.pl - mój blog
Greg H. (Guest)
on 2009-01-11 13:46
(Received via mailing list)
thanks - no way to get the class name & method name then?

2009/1/11 Radosław Bułat <removed_email_address@domain.invalid>
Radosław B. (Guest)
on 2009-01-11 15:17
(Received via mailing list)
2009/1/11 Greg H. <removed_email_address@domain.invalid>:
> thanks - no way to get the class name & method name then?
>

Method name is included in backtrace. e.backtrace returns array of
string, where each string has following form:
file:line in `method'
You can try to parse it (simply with regexp). I'm surprised that there
is no information about class but probably there is reason for that.

--
Pozdrawiam

Rados³aw Bu³at
http://radarek.jogger.pl - mój blog
Greg H. (Guest)
on 2009-01-11 22:39
(Received via mailing list)
thanks - wonder if given you have the method name, filename, line
number,
whether there is a way to work out the class you're in?  If it comes
down to
having to parse through the file itself it may get a bit messy
however...

2009/1/11 Radosław Bułat <removed_email_address@domain.invalid>
Rooger Pack (Guest)
on 2009-01-12 20:29
(Received via mailing list)
> no way to get class name [of exception backtraces].

There may be some room to make this better in 1.9, but for now you have
to [ugh]
reparse or do whatever's necessary.

Some possibly helpful links:
http://github.com/rogerdpack/ruby_backtracer/tree/master
http://eigenclass.org/hiki/method+arguments+via+in...
This topic is locked and can not be replied to.