[英]Exception is only caught with `rescue` at the end of the line but not when using a `begin rescue` block
我的聲明失敗了:
result = service.load_data()
現在以下抑制錯誤,然后我可以檢查nil
result = service.load_data() rescue nil
但是當我執行以下操作時,初始錯誤會被拋到UI,我不會得到異常的details
。
begin
result = service.load_data()
rescue => details
logger.fatal "Failed to load the data: #{details}"
end
我確信我必須缺少一個愚蠢的細節,但我似乎無法在這里發現問題。 那么為什么不調用rescue
區?
更新:我得到的錯誤是這樣的:
getaddrinfo: nodename nor servname provided, or not known
begin
result = service.load_data()
rescue AnExceptionKlass => details # here the name is SocketError
logger.fatal "Failed to load the data: #{details}"
end
使用上面的。
試圖在這里復制錯誤,如下所示:
require 'net/http'
Net::HTTP.start('http://www.google.com') do |http|
response = http.get('/')
puts response
end
#=> getaddrinfo: No such host is known. (SocketError)
修正如下:
require 'net/http'
begin
htt = Net::HTTP.start('http://www.google.com')
response = htt.get('/')
puts response
rescue SocketError => details # or the Exception class name may be SocketError
p "Failed to load the data: #{details}"
end
#=> "Failed to load the data: getaddrinfo: No such host is known. "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.