微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在下面的代码
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

我想打印一个警告,指出错误的类型和消息,而不会向每个救援条款添加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

解决方法

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

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

原文地址:https://www.jb51.cc/ruby/273113.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐