在迭代器内的处理过程中引发错误,并继续进行下一项



假设我正在循环数组中的一些项,如下所示:

class ImportHandler
attr_reader :files
 def initialize
   @files = ['file_path','file_path2']
 end
 def process
    files.each do |file|
     begin
      if validate(file) && decrypt(file)
       import(file)
       upload(file)
      end
     rescue Exception => e
      raise e
     end
    end
 end
 def validate(file)
  FileValidator.new(file).run
 end
end

上面看到的所有操作,如validate、decrypt、import和upload,都是创建新对象的方法。

假设在这些步骤中的任何一个都可能失败(文件无效,无法解密等)。我想在任何这些进程中引发错误,但要确保它返回(返回到正在进行迭代的类)并继续到数组中的下一个文件路径。

例如,在validate类(如果在上面的例子中不清楚的话,它是用于验证的类)中,我可能有这样的内容:

class FileValidator
   attr_reader :file
    def initialize(file)
      @file = file
    end
   def hash_validation(file_path)
     unless file.hash == metdata_hash
       raise "This file has been tampered with!"
     end
   end
end

我想引发该错误,但要确保程序返回到迭代,并继续处理数组中的下一个对象。有没有简单的方法可以做到这一点?

只需将代码包装在begin/rescue/end中,救援程序将捕获错误,然后继续进行下一次迭代:

files.each do |file|
  begin
    if validate(file) && decrypt(file)
     import(file)
     upload(file)
    end
  rescue
   // do nothing or maybe provide some output to know that error occured
  end
end

还有一个retry,您可以从救援中调用以再次尝试当前迭代。当然,您可能需要一些条件,如重试计数等,以确保您不会陷入无限循环

最新更新