从MongoWriteException获取错误代码,重复键错误



我正在尝试检测通过C#和MongoDB.Driver编写的代码中的重复键插入错误。

这种情况的错误处理是否正确?(实体 ID 列上有一个唯一的索引(

public class Entity
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string EntityId { get; set; }
}
...
public async Task<string> CreateEntityAsync(string entityId)
{
var entity = new Entity
{
EntityId = entityId,
};
try
{
await Collection.InsertOneAsync(peer);
}
//according to https://docs.mongodb.com/manual/core/index-unique error 11000 should be raised.
catch (MongoWriteException ex) when (GetErrorCode(ex) == 11000)
{
//custom error handling
}
return entity.Id;
}
private int GetErrorCode(MongoWriteException ex)
{
return (ex.InnerException as MongoBulkWriteException)?.WriteErrors.FirstOrDefault()?.Code ?? 0;
}

更干净的代码是捕获MongoWriteException并按类别过滤,示例代码:

try {
await _collection.InsertOneAsync(playerIn);
} catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) {
// Custom error handling
}

最新更新