[JAVA-1821] findAndModify() with upsert throws wrong exception for duplicate key errors Created: 20/May/15  Updated: 03/Oct/16  Resolved: 03/Oct/16

Status: Closed
Project: Java Driver
Component/s: Error Handling, Write Operations
Affects Version/s: 2.13.1
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Ivan Todoroski Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Java Source File DuplicateKeyBug.java    
Issue Links:
Duplicate
is duplicated by JAVA-517 DuplicateKey exception not properly t... Closed

 Description   

When doing an update() operation with upsert=true, sometimes you can get into a situation where it tries to insert a duplicate key into the collection.

When this happens, update() will throw a DuplicateKeyException, as expected.

However, if you attempt the exact same modification using findAndModify() instead of update(), and you trigger the exact same duplicate key condition, you won't get a DuplicateKeyException, as you might expect. You get a CommandFailureException instead.

This can introduce subtle bugs if you have some existing logic that might depend on catching a DuplicateKeyException during atomic update() operations, and you decide you need some extra functionality from findAndModify(), while expecting your existing DuplicateKeyException handler to keep working as before...

See the attached DuplicateKeyBug.java for a self-contained example of this problem. Run it against org.mongodb:mongo-java-driver:2.13.1.

The expected output from this program would be:

Duplicate key detected during update(upsert=true), as expected
Duplicate key detected during findAndModify(upsert=true), as expected

Instead, I get this output when I run it:

Duplicate key detected during update(upsert=true), as expected
Unexpected exception from findAndModify(upsert=true): com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "value" :  null  , "errmsg" : "exception: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.duplicate-key-bug.$_id_  dup key: { : 123 }" , "code" : 11000 , "ok" : 0.0}



 Comments   
Comment by Jeffrey Yemin [ 03/Oct/16 ]

While I agree that findAndModify should have thrown a DuplicateKeyException, changing it now would break compatibility with existing users who are already expecting a different exception.

So unfortunately this will be closed as Won't Fix.

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