首页 > 技术文章 > rails timeout 异常

x123811 2017-05-16 14:24 原文

发现经常有”超时“的错误信息,如/usr/lib/ruby/1.8/timeout.rb:54:in `rbuf_fill': execution expired (Timeout::Error),恩,应该是网络不稳定或者是服务器响应太慢的结果,需要捕获下这个异常并做些处理,记录如下: 

需要注意的是,Timeout::Error不是StandardError的子类, 而是继承至 Interrupt class,所以捕获的时候,需要格外注意,演示如下: 



require 'net/pop3'   
begin   
  Net::POP3.auth_only(@server, @port, @username, @password)   
rescue => e   
  write_error_to_logfile(e)   
  do_something_sensible   
end   


看上面的这段代码,当POP3服务器不能及时响应的时候,所触发的异常并不能被下面捕获到,原因就是上面说的,再看正确的处理代码: 



require 'net/pop3'   
begin   
  Net::POP3.auth_only(@server, @port, @username, @password)   
rescue => e   
  write_error_to_logfile(e)   
  do_something_sensible   
rescue Timeout::Error => e   
  write_error_to_logfile(e)   
  do_something_sensible_for_timeout   
end   


这段代码可以正常工作,并按照我们的意愿来处理了。 

如果您知道对方的服务器会比较慢的响应,或者你知道网络状态不好,你可以单独设置这个TimeOut的时间,代码如下: 


require 'timeout'   
   
...   
...   
begin   
  timeout(60) do   
     resp, body=3Dh.get('/index.html')   
     puts body   
  end   
rescue TimeoutError   
       puts "Timed Out"   
end  





或者这样:(来源:http://textsnippets.com/posts/show/868) 


http = Net::HTTP.new(url.host, url.port)   
http.read_timeout=time_out  

转自 http://hlee.iteye.com/blog/353732

推荐阅读