3
def checkdomains
  @domains = Domain.all

  #@domains.where(:confirmed => "yes").each do |f|
  @domains.each do |f|
    r = Whois.whois(f.domain)
    if r.available? == true
      EmailNotify.notify_email(f).deliver
    end
  end
end

This method crashes when it comes upon an invalid url (the whois gem gives an error), and doesn't keep on checking the rest of the domains. Is there any way I can have it continue to check the rest of the domains even if it crashes on one? At least until I can sort out phising out each domain.

Mischa
  • 42,876
  • 8
  • 99
  • 111
Rickmasta
  • 439
  • 1
  • 7
  • 16

3 Answers3

9
  @domains.each do |f|
    begin
      r = Whois.whois(f.domain)
      if r.available? == true
        EmailNotify.notify_email(f).deliver
      end
    rescue Exception => e
      puts "Error #{e}"
      next   # <= This is what you were looking for
    end
  end
cbron
  • 4,036
  • 3
  • 33
  • 40
3

When you say

crashing out

I assume you mean that you are getting an exception raised. If this is the case then just trap the exception, do what you want with it (Store the address in a bad_email table or whatever) then carry on doing what you are doing. Your log file will tell what exception is being raised so you know what your rescue statement should be

so

begin
  r = Whois.whois(f.domain)
  if r.available? == true
  EmailNotify.notify_email(f).deliver
rescue WhateverException
  #do something here like re raise the error or store the email address in a bad_emails table or do both just simply do nothing at all
end

If you are referring to something else like the whole app dying then I haven'ty got a clue and there is not enough info to advise further. Sorry

jamesc
  • 12,423
  • 15
  • 74
  • 113
  • I have no idea what I would do for the rescue though, I just want it to continue onto the next domain. – Rickmasta Aug 09 '11 at 03:05
  • 1
    You could do whatever you want or nothing at all. Storing the bad email address in bad_email table so you can filter them out more easily next time seems like a reasonable enough thing to do. I'll update my answer – jamesc Aug 09 '11 at 03:14
  • 2
    You could put `next` in the rescue. This tells the iteration to go to the next item. But since you have begin-rescue-end inside the iteration, putting nothing inside the rescue works too. – Mischa Aug 09 '11 at 03:46
  • @mischa - Thank you for pointing that out, I'd totally overlooked using `next` – jamesc Aug 09 '11 at 03:54
2

As jamesw suggests, you can wrap the statements in an exception handler, dealing with them as they occur. Let me suggest further that, wherever your program gets these (possibly invalid) domain names, you validate them as soon as you get them, and throw out the invalid ones. That way, by the time you reach this loop, you already know you're iterating over a list of good domains.

EDIT: For domain name validation, check here.

Community
  • 1
  • 1
plasticsaber
  • 232
  • 1
  • 4