0

我有一个失败的声明:

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
4

1 回答 1

2
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. "
于 2013-04-24T17:43:05.750 回答