只有当“救援”位于线路末端时才会捕捉到异常,而当使用“开始救援”块时则不会捕捉到异常



我有一个失败的语句:

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. "

相关内容

最新更新