`

Rails Timeout 异常处理

阅读更多
发现经常有”超时“的错误信息,如/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   




分享到:
评论
1 楼 uglyduck^swam 2010-04-21  
这些代码的路径是什么?

相关推荐

Global site tag (gtag.js) - Google Analytics