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

问题描述 投票:0回答:1

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

对于这种情况,错误处理是否正确? (EntityId列有唯一索引)

    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;
    }
mongodb mongodb-.net-driver
1个回答
0
投票

更清晰的代码是捕获 MongoWriteException 并按类别使用 when 进行过滤,示例代码:

    try
    {
        await _collection.InsertOneAsync(playerIn);
    }
    catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
    {
        // Custom error handling
    }
© www.soinside.com 2019 - 2024. All rights reserved.