【发布时间】: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