Ask*_*kar 2 ruby error-handling exception-handling mongodb
有没有在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>'
Run Code Online (Sandbox Code Playgroud)
我有这个错误,因为我正在尝试插入一个文件,其中包含mongodb数据库中已经存在的id,我只是想知道如何处理ruby中与mongodb相关的异常.例如,如果发生异常,那么我将更改哈希的id,然后重新尝试插入它.
如何抢救块会是什么样子?
红宝石块看起来像:
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
Run Code Online (Sandbox Code Playgroud)
但是,如果要更新已存在的记录,为什么不使用upsert.
如果你要创建一个新记录,为什么不让mongod创建_id?