Home Ruby 2.3 - Adding Timeout error and notification to net:http request
Reply: 0

Ruby 2.3 - Adding Timeout error and notification to net:http request

user2717 Published in May 22, 2018, 12:13 am

I have a working system to produce errors and send them to be used by Active Admin.

For example in Active admin, for a specific page of our CMS, the page might execute :

url_must_be_accessible("http://www.exmaple.com", field_url_partner, "URL for the partner")

And this uses the code below to send to the Active Admin Editor different type of errors notifications:

module UrlHttpResponseHelper

  def url_must_be_accessible(url, target_field, field_name)      
    if url
      url_response_code = get_url_http_response(url).code.to_i
      case url_response_code
      when -1                                                         
        # DNS issue; website does not exist; 
          "#{field_name}: DNS Problem -> #{url} website does not exist")
      when 200
      when 304
          "#{field_name}: #{url} sends #{url_response_code} response code")

  def get_url_http_response(url)  
    uri = URI.parse(URI.encode(url))
    request = Net::HTTP.get_response(uri)
    return request
  rescue Errno::ECONNREFUSED, SocketError => e
    OpenStruct.new(code: -1)


In local mode, this worked great! But in production, we're on Heroku and when a request pn Heroku goes beyond 30 seconds like if you try on this link "http://www.exmaple.com", the app crashes with a "H12 error".

I'd like to add to the code above two things - timeouts: i think i need both read_timeout and open_timeout and that the read_timeout + open_timeout should be < to 30 seconds, with let's take some security , better < 25seconds

  • if the request is still "going" after 25 seconds, then avoid reaching 30seconds by giving up/dropping the request

  • and catch this "we dropped the request intentionnally because risk of timeout" by sending a notification to the user. I'd like to use my current system with somehting along the lines of:

     rescue Errno::ECONNREFUSED, SocketError => e
        OpenStruct.new(code: -7) # = some random number
    case url_response_code
    when -7
              "#{field_name}: We tried to reach #{url} but this takes too long and risks crashing the app. please check the url and try again.")

How can I create a code like -1 but another one to rescue this "timeout"/"drop the request attempt" that I myself enforce.

Tried but nothing works. I don't manage to create the code for catch and drop this request if reaches 25 seconds...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302677 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO