engin
engin

Reputation: 31

How do I check the url for socket error ruby

 uri = URI("http://#{url}")
 res = Net::HTTP.get_response(uri) ### Code here

I read the path URLs from the txt file. When a url socket error or timeout error is given the program closes. To prevent it, I want to check that it does not give a url socket error.

uri = URI("http://#{url}")
if (uri== worked ) ### What should I use here?
  res = Net::HTTP.get_response(uri)
end

Upvotes: 1

Views: 111

Answers (1)

Sculper
Sculper

Reputation: 755

Instead of an if statement, you should use an exception handler for this. Assuming the errors you're expecting are SocketError and Errno::ETIMEDOUT, that would look something like this:

begin
  # code that might raise the error
rescue SocketError => e
  # run this code in the event of a socket error
rescue Errno::ETIMEDOUT => e
  # run this code in the event of a timeout
ensure
  # run this code unless an error is raised that isn't accounted for
end 

Upvotes: 1

Related Questions