续集gem:优雅地处理无效的日期值

时间:2012-12-17 18:56:13

标签: ruby sequel

我是一个红宝石菜鸟,我正在尝试使用Sequel和data_objects适配器处理一些博客文章:

DB = Sequel.connect('do:mysql://user:pass@localhost/database')

db[posts_query].each do |post|
  puts post
end

但我得到Sequel::InvalidValue例外,抱怨日期栏:

/usr/lib/ruby/1.9.1/time.rb:202:in `local': ArgumentError: argument out of range (Sequel::InvalidValue)
    from /usr/lib/ruby/1.9.1/time.rb:202:in `make_time'
    from /usr/lib/ruby/1.9.1/time.rb:271:in `parse'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/core.rb:295:in `string_to_datetime'

我试图抓住异常:

begin
  db[posts_query].each do |post|
      puts post
  end
rescue Sequel::InvalidValue => e
  puts e.inspect
end

但这没什么用。

如何找出哪一行的值不正确?

此外,是否有办法进行此迭代,以便我可以捕获异常但继续循环其余的行?

更新

我切换到mysql2适配器,现在我至少可以看到无效日期:

/var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/mysql2.rb:154:in `each': Mysql2::Error: Invalid date: 2008-04-00 00:00:15 (Sequel::DatabaseError)
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/mysql2.rb:154:in `block in fetch_rows'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/mysql2.rb:89:in `_execute'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/shared/mysql_prepared_statements.rb:34:in `block in execute'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/database/connecting.rb:236:in `block in synchronize'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/connection_pool/threaded.rb:104:in `hold'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/database/connecting.rb:236:in `synchronize'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/shared/mysql_prepared_statements.rb:34:in `execute'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/dataset/actions.rb:778:in `execute'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/mysql2.rb:171:in `execute'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/adapters/mysql2.rb:140:in `fetch_rows'
    from /var/lib/gems/1.9.1/gems/sequel-3.42.0/lib/sequel/dataset/actions.rb:154:in `each'
    from wordpress_importer.rb:112:in `process'
    from wordpress_importer.rb:308:in `<main>'

1 个答案:

答案 0 :(得分:3)

你可以发布更多的回溯吗?您需要查看正在调用的内容string_to_datetime

另外,我建议不要使用do / mysql适配器,除非你有特殊需求需要它。请改用mysql或mysql2适配器。如果错误是由MySQL数据库中的伪造日期时间引起的,那么您可能需要使用mysql2适配器或使用mysql适配器并设置DB.convert_invalid_date_time = nil