简体   繁体   中英

Skip a http request if response if taking too long with ruby

I have an array of urls. I'm going through each one, sending a get request and printing the response code. Here is part of the code:

arr.each do |url|
  res = Faraday.get(link.href)
  p res.status
end

However sometimes I get to url, it times out and crashes. Is there a way to tell ruby "if I don't get a response in a certain amount of time then skip to the next url?"

You could add a timeout like this:

require 'timeout'

arr.each do |url|
  begin
    Timeout.timeout(5) do # a timeout of five seconds 
      res = Faraday.get(link.href)
      p res.status
    end
  rescue Timeout::Error
    # handle error: show user a message?
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM