You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何区分ConditionalCheckFailedException是条件检查还是乐观锁导致?

区分ConditionalCheckFailedException的触发原因

要区分ConditionalCheckFailedException是普通条件检查失败还是乐观锁机制触发的,目前AWS SDK没有提供原生的区分字段,但可以通过以下可靠方法实现:

  • 自定义请求标记
    在发起DynamoDB请求时,给请求附加自定义元数据标记,明确该请求是乐观锁场景还是普通条件检查场景。当异常抛出时,从请求上下文读取标记即可判断成因。

    示例代码(.NET SDK):

    var updateRequest = new UpdateItemRequest
    {
        TableName = "YourTable",
        Key = new Dictionary<string, AttributeValue> { { "ItemId", new AttributeValue { S = "ITEM_001" } } },
        UpdateExpression = "SET #content = :newContent, #version = #version + :inc",
        ExpressionAttributeNames = new Dictionary<string, string> 
        { 
            { "#content", "Content" }, 
            { "#version", "Version" } 
        },
        ExpressionAttributeValues = new Dictionary<string, AttributeValue>
        {
            { ":newContent", new AttributeValue { S = "Updated content" } },
            { ":inc", new AttributeValue { N = "1" } },
            { ":expectedVersion", new AttributeValue { N = "5" } }
        },
        ConditionExpression = "#version = :expectedVersion" // 乐观锁条件
    };
    
    // 添加自定义标记,标识这是乐观锁请求
    updateRequest.Metadata.Add("RequestCategory", "OptimisticLock");
    
    try
    {
        await dynamoDbClient.UpdateItemAsync(updateRequest);
    }
    catch (ConditionalCheckFailedException ex)
    {
        if (updateRequest.Metadata.TryGetValue("RequestCategory", out var category) 
            && category == "OptimisticLock")
        {
            // 乐观锁场景:执行专属重试逻辑
            RetryOptimisticLockRequest(updateRequest);
        }
        else
        {
            // 普通条件检查失败:不执行重试或走其他处理逻辑
            HandleConditionalCheckFailure(ex);
        }
    }
    
  • 不推荐:解析异常消息
    虽然部分场景下异常消息可能包含模糊特征,但AWS并未保证消息格式的稳定性,SDK版本更新可能导致解析逻辑失效,因此不建议依赖这种方式。

需要注意的是,当前AWS SDK仍未在ConditionalCheckFailedException中添加原生的成因区分属性,自定义标记是最可靠的方案。

内容的提问来源于stack exchange,提问作者Masuri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:52:44