Golang DynamoDB SDK单写操作条件校验失败,如何获取失败详情?
问题描述
我正在使用Golang SDK(版本:v1.45.26)调试DynamoDB条件校验错误,希望获取单写操作(UpdateItem)中条件校验失败的具体原因,但仅能看到错误信息:"The conditional request failed"。在UpdateItemInput中设置ReturnValuesOnConditionCheckFailure: ALL_OLD参数后,仍未返回任何失败原因的具体信息。但在TransactWriteItems操作中使用相同参数时,却能查看到条件校验失败的具体原因。请问如何在单写操作中也获取这些详情?
使用的代码如下:
input := &dynamodb.UpdateItemInput{ TableName: aws.String("DummyTable"), Key: keyAttr, ExpressionAttributeValues: updateExpr.Values(), ExpressionAttributeNames: updateExpr.Names(), ConditionExpression: updateExpr.Condition(), ReturnValues: aws.String(dynamodb.ReturnValueAllOld), UpdateExpression: updateExpr.Update(), ReturnValuesOnConditionCheckFailure: aws.String(dynamodb.ReturnValuesOnConditionCheckFailureAllOld), } output, err := dl.ddbI.UpdateItem(input)
解决方案
要在单写操作(如UpdateItem)中获取条件校验失败的具体详情,需按以下步骤处理:
升级Golang SDK版本:你当前使用的v1.45.26版本不支持DynamoDB单写操作返回条件失败详情的特性(该特性2023年6月推出)。需将
aws-sdk-go升级到v1.46.0及以上版本,该版本开始支持在单写操作失败时返回具体校验失败原因。错误类型断言提取详情:SDK升级后,当条件校验失败时,错误会被封装为
dynamodbtypes.ConditionalCheckFailedException类型,你需要对错误进行类型断言,从而获取Details字段中的具体失败原因。示例代码如下:
output, err := dl.ddbI.UpdateItem(input) if err != nil { var condErr *dynamodbtypes.ConditionalCheckFailedException if errors.As(err, &condErr) { // 打印具体失败详情 fmt.Printf("条件校验失败详情: %v\n", condErr.Details) // 获取失败时的旧数据(需保持ReturnValuesOnConditionCheckFailure参数配置) fmt.Printf("失败时的旧数据: %v\n", condErr.Item) } else { // 处理其他类型错误 fmt.Printf("其他错误: %v\n", err) } return err }
- 确认参数配置:确保
ReturnValuesOnConditionCheckFailure参数设置正确(你当前的代码已设置为ALL_OLD,无需修改),该参数会返回校验失败时的项目旧数据,配合错误详情能更清晰定位问题。
内容的提问来源于stack exchange,提问作者Lawliet
相关产品推荐
相关产品推荐

