2

有没有在 ruby​​ 中处理 mongodb 相关异常的好例子?在这种情况下,我有:

/home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/networking.rb:89:in `send_message_with_gle': 11000: E11000 duplicate key error index: somedb.somecoll.$_id_  dup key: { : "some_id" } (Mongo::OperationFailure)
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1108:in `block in insert_documents'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:33:in `block in instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:65:in `instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:32:in `instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1106:in `insert_documents'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:375:in `insert'
    from lib/tasks/getorders.rb:47:in `block in <main>'
    from lib/tasks/getorders.rb:25:in `each'
    from lib/tasks/getorders.rb:25:in `<main>'

我遇到这个错误是因为我试图插入一个 id 已经存在于 mongodb 数据库中的文档,我只想知道如何在 ruby​​ 中处理与 mongodb 相关的异常。例如,如果发生异常,那么我会更改哈希的 id,然后重新尝试插入它。

救援块会是什么样子?

4

3 回答 3

6

红宝石块看起来像:

begin
  # your operation
rescue Mongo::OperationFailure => e
  if e.message =~ /^11000/
    puts "Duplicate key error #{$!}"
    # do something to recover from duplicate
  else
    raise e
  end
end
# the rest of the exceptions follow ..
# if you just care about the dup error
# then ignore them
#rescue Mongo::MongoRubyError
#  #Mongo::ConnectionError, Mongo::ConnectionTimeoutError, Mongo::GridError, Mongo::InvalidSortValueError, Mongo::MongoArgumentError, Mongo::NodeWithTagsNotFound
#  puts "Ruby Error :  #{$!}"
#rescue Mongo::MongoDBError
#  # Mongo::AuthenticationError, Mongo::ConnectionFailure, Mongo::InvalidOperation, Mongo::OperationFailure
#  puts "DB Error :  #{$!}"
#rescue Mongo::OperationTimeout
#  puts "Socket operation timeout Error :  #{$!}"
#rescue Mongo::InvalidNSName
#  puts "invalid collection or database Error :  #{$!}"
#end

但是,如果您要更新已经存在的记录,为什么不使用upsert

如果您正在创建新记录,那么为什么不让 mongod 创建 _id 呢?

于 2013-06-05T14:34:48.703 回答
0

也可以使用写关注点。

@mongo_client.save({:doc => 'foo'}, {:w => 0}) # writes are not acknowledged

不过,这还不如救援。

于 2013-10-24T18:10:37.533 回答
0

如果您的 ruby​​ 驱动程序是>= 2.0.0,您应该Mongo::Error对大多数 mongodb 相关异常使用 class。这是您的rescue块的外观:

begin
  # Document insert code
rescue Mongo::Error => e
  if e.message.include? 'E11000'
    # Change the id of the hash & re-try to insert it
  end
end
于 2016-07-28T14:28:50.447 回答