Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-4812

Improve docs or improve duplicate key error handling

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: None
    • None

      So when I first wrote my code for signing up a user, I had written this in case a user tried to sign up from two phones at the same time. The code is below

              try

      {             await _usersCollection.InsertOneAsync(user);             return true;         }

      catch (MongoDuplicateKeyException) { return false; }

      Yesterday, I had to create a custom account for the mobile app reviewer so that they don't have to use their own email. The review failed. I wondered why today. I looked at the logs, ran the test myself, and at first it worked and then on subsequent tries it did not. I looked at the logs and saw duplicate key error. I saw my source code it was as seen above. I was confused. Miraculously, I found this on stack overflow so I was able to fix my code even though the fault was MongoDB for having an exception called DuplicateKeyException that doesn't actually catch a duplicate key exception.

              } catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)

      {             return false;         }

      I suggest that the following is documented as an example in the API docs or in the usage docs or better yet, I hope the driver is updated so that the code in the first block works because the second block is too verbose to know by heart.

            Assignee:
            oleksandr.poliakov@mongodb.com Oleksandr Poliakov
            Reporter:
            elopez@splitthetank.com Elijah Lopez
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: