如何在ruby中显示错误类型?

Flu*_*ffy 27 ruby exception

在以下代码中

begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
end
Run Code Online (Sandbox Code Playgroud)

我想打印一个警告,说明错误的类型和消息,而不是为每个救援条款添加print语句,例如

begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
???
 print "An error of type #{???} happened, message is #{???}"
end
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 59

begin
  raise ArgumentError, "I'm a description"
rescue Exception => ex
  puts "An error of type #{ex.class} happened, message is #{ex.message}"
end
Run Code Online (Sandbox Code Playgroud)

打印:ArgumentError类型的错误发生了,消息是我的描述

  • 观察它,除非你完全意识到它的含义,否则不要捕捉异常.使用rescue => ex(Convention over configuration)作为默认的cacher. (11认同)
  • 然后,如果您仍然需要针对不同类型的错误进行特定处理,那么您可以使用case..when. (3认同)

Uly*_* BN 7

如果你想显示原始的回溯并突出显示,你可以利用Exception#full_message

\n
\n

full_message(突出显示: bool, 顺序: [:top 或 :bottom]) \xe2\x86\x92 字符串

\n

返回异常的格式化字符串。返回的字符串的格式与 Ruby 将未捕获的异常打印到 stderr 时使用的格式相同。

\n

如果高亮true默认的错误处理程序,则会将消息发送到 tty。

\n

order必须是:top:bottom,并将错误消息和最里面的回溯放在顶部或底部。

\n

这些选项的默认值取决于$stderr调用tty?的时间。

\n
\n
begin\n  raise ArgumentError, "I\'m a description"\nrescue StandardError => e\n  puts e.full_message(highlight: true, order: :top)\nend\n
Run Code Online (Sandbox Code Playgroud)\n


小智 5

我的打印错误类型、消息和跟踪版本:

begin
    some_statement
rescue => e
    puts "Exception Occurred #{e.class}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    Rails.logger.error "Exception Occurred #{e.class}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
end
Run Code Online (Sandbox Code Playgroud)