【问题标题】:How to continue processing a block in Ruby after an exception?异常后如何继续处理Ruby中的块?
【发布时间】:2013-07-02 19:07:20
【问题描述】:

我正在尝试处理一些非常大的制表符分隔文件。流程是:

  begin
   Dir["#{@data_path}*.tsv"].each do |file|
       begin              
          CSV.foreach(file, :col_sep => "\t") do |row|

           # assign columns to model and save

           end
           @log.info("Loaded all files into MySQL database illu.datafeeds")
       rescue Exception => e
             @log.warn("Unable to process the data feed: #{file} because #{e.message}")
             next
       end
   end

但是,当我执行此操作时,我收到以下错误:

Unable to process the file: /Users/XXXXX_2013-06-12.tsv because Illegal quoting in line 153.

文件太大,我无法进入并修复错误行。即使有错误行,我也希望该过程继续循环并处理文件。

有什么建议吗?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby csv


    【解决方案1】:

    只是... rescue nil导致错误的行

    你甚至可以用记录器记录它

    循环前:

    error_log ||= Logger.new("#{Rails.root}/log/my.log")
    

    在循环内部而不是仅仅使用rescue nil

    rescue error_log.info(row.to_s)
    

    如果您在文件开始解析之前(在 .foreach 过程之前)遇到错误,您可以将其作为原始文件打开并稍后以 CSV 格式读取 - 在循环内(如提到的here

    ..或者只是拯救完整的文件解析过程

     CSV.foreach(file, :col_sep => "\t") do |row|
        ...
     end rescue error_log.info(row.to_s) 
    

    【讨论】:

    • 我没有找到你建议的方法成功。如果我更改为救援 nil,块仍然失败,我只是没有收到错误消息。如果我使用 error_log.info(row.to_s) 它会失败,因为 (row.to_s) 在 CSV.foreach 之外不存在。
    • 我试过这个。开始目录["#{@data_path}*.tsv"].each do |file|开始 CSV.foreach(file, :col_sep => "\t") 做 |row| # do stuff end @log.info("Loaded all files") rescue @log.info(row.to_s) end end end
    • 我实际上是通过将行错误捕获移动到 CSV.foreach 循环内的开始救援块来实现的。谢谢。
    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2019-09-05
    • 2010-09-13
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多