Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching line numbers in ruby exceptions

Tags:

exception

ruby

Consider the following ruby code

test.rb:

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

For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that?

like image 909
anshul Avatar asked Sep 23 '08 05:09

anshul


People also ask

How do you rescue all exceptions in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

Does Ruby have try catch?

In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).

How Exception handling is performed in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception. puts 'This is Before Exception Arise!'


1 Answers

p e.backtrace  

I ran it on an IRB session which has no source and it still gave relevant info.

=> ["(irb):11:in `foo'",      "(irb):17:in `irb_binding'",       "/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'",       "/usr/lib64/ruby/1.8/irb/workspace.rb:52"] 

If you want a nicely parsed backtrace, the following regex might be handy:

p x.backtrace.map{ |x|         x.match(/^(.+?):(\d+)(|:in `(.+)')$/);      [$1,$2,$4]  }  [   ["(irb)", "11", "foo"],    ["(irb)", "48", "irb_binding"],    ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", "irb_binding"],    ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", nil] ] 

( Regex /should/ be safe against weird characters in function names or directories/filenames ) ( If you're wondering where foo camefrom, i made a def to grab the exception out :

>>def foo >>  thisFunctionDoesNotExist >> rescue Exception => e  >>   return e  >>end      >>x = foo  >>x.backtrace 
like image 140
Kent Fredric Avatar answered Sep 19 '22 06:09

Kent Fredric