josh
josh

Reputation: 135

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?"

Upvotes: 1

Views: 699

Answers (1)

spickermann
spickermann

Reputation: 107047

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

Upvotes: 4

Related Questions