If you do this using the async method, then the brp output will work (and is preferred), otherwise you can call Wait() on the Task returned from the InsertOneAsync call InsertOneAsync that your application remains long enough to see a duplicate key exception:
commandsCollection.InsertOneAsync(doc).Wait();
If the insertion fails due to a duplicate key, Wait() throw an AggregateException that contains a MongoWriteException that contains the duplicate key's data.
try { commandsCollection.InsertOneAsync(doc).Wait(); } catch(AggregateException aggEx) { aggEx.Handle(x => { var mwx = x as MongoWriteException; if (mwx != null && mwx.WriteError.Category == ServerErrorCategory.DuplicateKey) {
Similarly, if you use await , this will also throw an AggregateException .
To avoid the additional complexity of an AggregateException wrapping an mongo exception, you can call GetAwaiter().GetResult() instead of Wait() :
try { commandsCollection.InsertOneAsync(doc).GetAwaiter().GetResult(); } catch(MongoWriteException mwx) { if (mwx.WriteError.Category == ServerErrorCategory.DuplicateKey) {
Johnnyhk
source share