[JAVA-517] DuplicateKey exception not properly thrown through findAndModify Created: 07/Feb/12  Updated: 28/Oct/15  Resolved: 28/Oct/15

Status: Closed
Project: Java Driver
Component/s: API
Affects Version/s: 2.7.3
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Philipp Heinze Assignee: Unassigned
Resolution: Duplicate Votes: 1
Labels: DuplicateKey, MongoException, findAndModify
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Java 6, Fedora 16


Issue Links:
Duplicate
duplicates JAVA-1821 findAndModify() with upsert throws wr... Closed
Related
related to JAVA-757 Exceptions throws for GLE should cont... Closed

 Description   

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.



 Comments   
Comment by Jeffrey Yemin [ 28/Oct/15 ]

Closing as duplicate of JAVA-1821

Comment by Jeffrey Yemin [ 27/Feb/13 ]

Note that in 2.11.0 there will be a new public class CommandFailureException, from which you can get the CommandResult.

Comment by Jeffrey Yemin [ 07/Feb/12 ]

For findAndModify command, the 11001 error is wrapped in the lastErrorObject field of the server response, and it's being ignored. The main response is !ok(), which causes com.mongodb.CommandResult#getException to throw CommandFailure exception.

Solution may be to drill in to lastErrorObject field to look for the 11001 error code.

Generated at Thu Feb 08 08:52:29 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.