How can I monitor an endpoint's status with Ruby?

310 views Asked by At

I have several endpoints that I would like to monitor using Ruby. I would like to get their status codes (e.g. 200). I currently do this in this way

uri = URI.parse("http://example-domain.com")
response = Net::HTTP.get_response(uri)
status = response.code

However if the URL is not valid the process errors. I would like something which informs me the URL is not valid (ideally by returning "404" to the status variable)

Thanks in advance

2

There are 2 answers

0
Yevgeniy Anfilofyev On BEST ANSWER

Use rescue to catch exceptions. Something like this:

require 'uri'
require 'net/http'

uri = URI.parse("http://bad-example-domain.com")
begin
  response = Net::HTTP.get_response(uri)
rescue Exception => e
  p "Bad url: #{e}"
end
if response
  status = response.code
else
  status = "404"
end
p status

More about exceptions you could find in the Net, for example there: http://www.tutorialspoint.com/ruby/ruby_exceptions.htm

0
makhan On
uri = URI.parse("http://example-domain.com/wrong")
begin
  response = Net::HTTP.get_response(uri)
rescue Exception
end
status = response ? response.code : '0'