Se você estiver fazendo isso em um
async , então a resposta de Brduca funcionará (e é preferível), caso contrário você pode chamar Wait()
na Task retornado do InsertOneAsync call para garantir que seu aplicativo permaneça por tempo suficiente para ver a exceção de chave duplicada:commandsCollection.InsertOneAsync(doc).Wait();
Se a inserção falhar devido a uma chave duplicada, o
Wait() lançará um AggregateException que contém uma MongoWriteException que contém os detalhes da chave duplicada. try
{
commandsCollection.InsertOneAsync(doc).Wait();
}
catch(AggregateException aggEx)
{
aggEx.Handle(x =>
{
var mwx = x as MongoWriteException;
if (mwx != null && mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// mwx.WriteError.Message contains the duplicate key error message
return true;
}
return false;
});
}
Da mesma forma, se você estiver usando
await , que lançará um AggregateException também. Para evitar a complexidade adicional do
AggregateException envolvendo a exceção do mongo, você pode chamar GetAwaiter().GetResult() em vez de Wait() :try
{
commandsCollection.InsertOneAsync(doc).GetAwaiter().GetResult();
}
catch(MongoWriteException mwx)
{
if (mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// mwx.WriteError.Message contains the duplicate key error message
}
}