开发者

Make Ruby/Rails continue method after encountering error

开发者 https://www.devze.com 2023-03-26 15:30 出处:网络
def checkdomains @domains = Domain.all #@domains.where(:confirmed => \"yes\").each do |f| @domains.each do |f|
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
      Ema开发者_如何转开发ilNotify.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.


  @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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消