在红宝石例外中捕捉行号 [英] Catching line numbers in ruby exceptions

查看:233
本文介绍了在红宝石例外中捕捉行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下ruby代码

test.rb:

begin

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

为了进行调试,我想要救援块知道该文件的第4行出现错误。有没有干净的方法?

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?

推荐答案

p e.backtrace 

我运行在没有来源的IRB会话上,它仍然提供相关信息。

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]
]

(正则表达式/应该/对于函数名或目录/文件名中的奇怪字符)
(如果你想知道foo来自哪里,我做了一个def来抓取异常:

( 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

这篇关于在红宝石例外中捕捉行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆