使用AWS SDK调用UpdateTableCommand时遭遇ValidationException异常
解决DynamoDB UpdateTable设置删除保护时的ValidationException错误
你的问题出在:当传入的DeletionProtectionEnabled值和表当前的删除保护状态完全一致时,DynamoDB会判定没有任何实际的更新操作,因此抛出这个ValidationException。
虽然你确实传了DeletionProtectionEnabled参数,但如果表已经处于你要设置的状态(比如原本就开启了删除保护,你又传true),UpdateTable API会认为没有可更新的属性,触发这个错误。
修正方案
先查询表当前的删除保护状态,仅当状态与目标值不同时才执行更新操作:
this.#docClient = new DynamoDBClient({ region: REGION }); ... // 第一步:查询当前表的删除保护状态 const describeParams = { TableName: TABLE_NAME }; const describeResponse = await this.#docClient.send(new DescribeTableCommand(describeParams)); const currentDeletionProtection = describeResponse.Table.DeletionProtectionEnabled; // 第二步:仅当状态不一致时执行更新 if (currentDeletionProtection !== true) { const updateParams = { TableName: TABLE_NAME, DeletionProtectionEnabled: true }; const updateResponse = await this.#docClient.send(new UpdateTableCommand(updateParams)); console.log("删除保护更新成功", updateResponse); } else { console.log("表已处于目标删除保护状态,无需更新"); }
额外说明
如果你确认必须执行更新操作(即使状态一致),可以添加一个无实际影响的更新参数(比如临时修改TableClass再改回来),但这种做法不推荐,会额外消耗API调用次数,且没有实际意义。最合理的方式还是先查询再判断。
内容的提问来源于stack exchange,提问作者snack-overthrow
相关产品推荐
相关产品推荐

