我有这段代码来检查网站是启动还是关闭:
require 'net/http'
require 'uri'
res = Net::HTTP.get_response(URI.parse('http://www.saddsdsds.com/'))
case res
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
puts "ok"
else
puts "ok-error"
end
res2 = Net::HTTP.get_response(URI.parse('http://www.sads.com/'))
case res2
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
puts "ok"
else
puts "ok-error"
end
然而,代码在网站已知时工作正常,但当网站未知时(如res示例),代码中断了这个erorr:
`initialize': getaddrinfo: nodename nor servname provided, or not known (SocketError)
如何修复此问题,以便在地址不存在时,代码不会中断?
此外,这是检查网站是否在线的最佳方法吗?
由于
答案 0 :(得分:3)
使用begin..rescue
块围绕所有代码:
begin
...
rescue SocketError => e
puts "SocketError occurred: " + e
end