在以下代码中
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类型的错误发生了,消息是我的描述
如果你想显示原始的回溯并突出显示,你可以利用Exception#full_message:
\n\n\nfull_message(突出显示: bool, 顺序: [:top 或 :bottom]) \xe2\x86\x92 字符串
\n返回异常的格式化字符串。返回的字符串的格式与 Ruby 将未捕获的异常打印到 stderr 时使用的格式相同。
\n如果高亮是
\ntrue默认的错误处理程序,则会将消息发送到 tty。order必须是
\n:top或:bottom,并将错误消息和最里面的回溯放在顶部或底部。这些选项的默认值取决于
\n$stderr调用tty?的时间。
begin\n raise ArgumentError, "I\'m a description"\nrescue StandardError => e\n puts e.full_message(highlight: true, order: :top)\nend\nRun 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)
| 归档时间: |
|
| 查看次数: |
27403 次 |
| 最近记录: |