【问题标题】:How can I monitor an endpoint's status with Ruby?如何使用 Ruby 监控端点的状态?
【发布时间】:2015-06-09 07:25:16
【问题描述】:

我有几个想要使用 Ruby 监控的端点。我想获取他们的状态码(例如 200)。我目前是这样做的

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

但是,如果 URL 无效,则处理错误。我想要一些通知我 URL 无效的东西(最好将“404”返回给状态变量)

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby server endpoint


    【解决方案1】:

    使用rescue 捕获异常。像这样的:

    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
    

    有关您可以在网络中找到的异常的更多信息,例如:http://www.tutorialspoint.com/ruby/ruby_exceptions.htm

    【讨论】:

      【解决方案2】:
      uri = URI.parse("http://example-domain.com/wrong")
      begin
        response = Net::HTTP.get_response(uri)
      rescue Exception
      end
      status = response ? response.code : '0'
      

      【讨论】:

        猜你喜欢
        • 2013-12-22
        • 1970-01-01
        • 2019-04-10
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        相关资源
        最近更新 更多