一个网络连接(通常是 HTTP)从建立到返回的过程中有可能会出现很多种异常情况,比如 DNS 解析错误,比如服务器超时,比如 404……
SocketError, Timeout::Error, ActiveResource::TimeoutError, Errno::ECONNREFUSED, Errno::EHOSTDOWN, Errno::EHOSTUNREACH
,显然这并不是完整的列表……require 'net/http'
begin
content = Net::HTTP.get_response(URI('http://ruby-china.org')).body
rescue Exception
content = ''
end
require 'net/http'
begin
content = Net::HTTP.get_response(URI('http://ruby-china.org')).body
rescue SocketError, Errno::ETIMEDOUT, Errno::ECONNREFUSED,
Errno::EHOSTDOWN, Errno::EHOSTUNREACH
content = ''
end