Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Exceptions in a loop

Tags:

ruby

I have a ruby script that loops through a list of shortened urls (around 2,000 - 3,000 at a time). At the moment everything is peachy until a hit a url that is malformed, timedout etc. When an error occurs my script dies. How can I setup my loop to skip to the next record when/if such an error occurs.

my loop looks like this:

blah.foo do |barurl|
  mymethod(barurl)

my mymethod looks like this:

def mymethod(barurl)
  begin
    stuff
    ...
    return expandedurl
  rescue
    return "Problem expanding link"
  end
end

Should my begin/end logic be wrapped around my loop instead of the method?

like image 354
Colm Troy Avatar asked Oct 20 '25 05:10

Colm Troy


1 Answers

Because you need to skip the malformed url, you should use the exception message to control the loop

blah.foo do |barurl|
  begin
    mymethod(barurl)
  rescue YourTypeOfException
    next
  end
end

and inside the method raise the exception

def mymethod(barurl)
  stuff
  ...
  raise YourTypeOfException, "this url is not valid"
  ...
end
like image 193
megas Avatar answered Oct 21 '25 21:10

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!