【问题标题】:Raise an error during process within iterator and continue to next item在迭代器中的过程中引发错误并继续下一项
【发布时间】:2014-06-09 05:17:44
【问题描述】:

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

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 类中(如果在上面的示例中不清楚,它就是 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

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

【问题讨论】:

    标签: ruby error-handling


    【解决方案1】:

    只需将代码包装在 begin/rescue/end 中,rescue 就会捕获错误,然后继续下一次迭代:

    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,您可以从rescue 中调用以使用当前迭代重试。当然,您可能需要一些条件,例如重试次数等,以确保您不会陷入无限循环。

    【讨论】:

    • 我有类似的东西,但如果发生错误,程序仍然会停止运行。
    • 你能展示你有什么吗?停止时会出现什么样的错误?
    • rescue 后面可以跟要捕获的异常的参数列表(例如,ArgumentError);如果后面没有参数,则错误类型默认为StandardError。您还可以为不同的错误设置单独的rescue 子句,并且可以在每个参数列表之后添加=> var_name,在这种情况下,Ruby 会将错误消息分配给您指定的变量。
    • Graham,请具体说明错误:错误消息是什么以及您的代码的哪一行触发了它?
    • 我用更多代码更新了我的原始问题以显示我的设置。
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2020-09-09
    • 2010-12-23
    相关资源
    最近更新 更多