Timeout::Error isn't rescuing in Ruby
我仍然是Ruby的新手,我第一次尝试将Timeout用于某些HTTP功能,但显然我在某个地方错过了标记。 我的代码如下,但它不起作用。 相反,它引发了以下异常:
1 | C:/Ruby193/lib/ruby/1.9.1/net/http.rb:762:in `initialize': execution expired (Timeout::Error) |
这对我来说没有多大意义,因为它的超时代码部分包含在开始/救援/结束块中,特别是救出Timeout :: Error。 我做错了什么,或者Ruby中不支持的东西?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | retries = 10 Timeout::timeout(5) do begin File.open("#{$temp}\\http.log", 'w') { |f| http.request(request) do |str| f.write str.body end } rescue Timeout::Error if retries > 0 print"Timeout - Retrying..." retries -= 1 retry else puts"ERROR: Not responding after 10 retries! Giving up!") exit end end end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | retries = 10 begin Timeout::timeout(5) do File.open("#{$temp}\\http.log", 'w') do |f| http.request(request) do |str| f.write str.body end end end rescue Timeout::Error if retries > 0 print"Timeout - Retrying..." retries -= 1 retry else puts"ERROR: Not responding after 10 retries! Giving up!") exit end end |
使用retryable使这很简单
https://github.com/nfedyashev/retryable#readme
1 2 3 4 5 | require"open-uri" retryable(:tries => 3, :on => OpenURI::HTTPError) do xml = open("http://example.com/test.xml").read end |