Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-517

DuplicateKey exception not properly thrown through findAndModify

      Hi,

      when I try to insert a duplicate through this code:

      try

      { coll.findAndModify( queryId( document ).and( "p.revision" ).is( document.getRevision() ).get(), new BasicDBObject( "$set", mods ) ); }

      }
      catch ( MongoException e )
      {

      I'm not able to directly catch the DuplicateKey Exception, as findAndModify will not throw such exception. Rather it throws an CommandResult$CommandFailure, sadly this Exception isn't public so I can't catch it nor can I cast to it from MongoException.
      Catching a MongoException.DuplicateKey isn't working either as this exception isn't thrown at all. The only usage of DuplicateKey is within CommandResult.getException, but as CommandFailure isn't a subtype of CommandResult I neither can't cast to this, so the only way to currently find out what exception was thrown is to dig into the MongoException payload which looks like:

      com.mongodb.CommandResult$CommandFailure: command failed [command
      failed [findandmodify] { "serverUsed" : "pheinze-0830:27017" ,
      "lastErrorObject" : { "err" : "E11000 duplicate key error index:
      test.address.$ns_1_t_1_p.doc_id_1 dup key: { : \"_nn_\", : \"N\", :
      \"testPutPKTwice\" }" , "code" : 11000 , "n" : 0 , "connectionId" :
      44 , "ok" : 1.0} , "errmsg" : "E11000 duplicate key error index:
      test.address.$ns_1_t_1_p.doc_id_1 dup key: { : \"_nn_\", : \"N\", :
      \"testPutPKTwice\" }" , "ok" : 0.0}

      to check getLastError or to manually start another query to check if the key is already used. Neither of them feels to me that this is the way it's meant to be.

            Assignee:
            Unassigned Unassigned
            Reporter:
            pheinze Philipp Heinze
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: