I have this code to check if the site is up or down:
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
However, the code works fine when the site is known but when the site is unknown (like the res example), the code breaks with this erorr:
`initialize': getaddrinfo: nodename nor 开发者_JAVA百科servname provided, or not known (SocketError)
How can I fix this so when the address does not exist, the code does not break?
Also, is this the best way to check if a site is online?
Thanks
Surround all of that code with a begin..rescue
block:
begin
...
rescue SocketError => e
puts "SocketError occurred: " + e
end
精彩评论