在救援中输出错误(Ruby/Rails)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7270087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:53:38  来源:igfitidea点击:

Outputting errors in a rescue (Ruby/Rails)

ruby-on-railsrubyexception

提问by overtone

Just a quick question. I cant find it in the documentation.

只是一个简单的问题。我在文档中找不到它。

If I use a standard begin ... rescue, how do I print all the errors or stack trace into the rescue?

如果我使用标准begin ... rescue,如何将所有错误或堆栈跟踪打印到救援中?

e.g.:

例如:

begin 
    do x
rescue
    puts errors
end

Any ideas?

有任何想法吗?

回答by Peter Brown

There are at least two ways that I know of to get the error. The first is using a global variable: $! which is always set to the last error that occurred. The second is by explicitly capturing the error when you rescue:

我知道至少有两种方法可以得到错误。第一种是使用全局变量:$! 它始终设置为发生的最后一个错误。第二种是在救援时显式捕获错误:

begin
  # do something that fails...
rescue => error
  # error and $! are equivalent here
end

Either one will let you inspect or print out the backtrace using either:

任何一个都可以让您使用以下任一方法检查或打印回溯:

$!.backtrace # => array of backtrace steps
error.backtrace # => same error