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

如何捕获botocore中的BatchEntryIdsNotDistinct异常?

解决SQS DeleteMessageBatch异常捕获问题

问题原因

BatchEntryIdsNotDistinct是botocore基于服务JSON配置动态生成的异常类,并非预定义在botocore.errorfactory模块中的静态类,所以直接导入会失败。

两种捕获方式

方式一:捕获通用ClientError并判断错误码

这是最稳妥的方式,无需依赖动态生成的类:

import boto3
from botocore.exceptions import ClientError

sqs = boto3.resource('sqs', region_name='us-west-2')
queue = sqs.get_queue_by_name(QueueName='your-queue-name')

try:
    queue.delete_messages(Entries=your_delete_entries)
except ClientError as e:
    error_code = e.response['Error']['Code']
    if error_code == 'AWS.SimpleQueueService.BatchEntryIdsNotDistinct':
        # 处理重复ID的逻辑
        print("删除条目存在重复ID,请检查Entries中的Id字段")
    else:
        # 处理其他SQS错误
        raise

方式二:获取动态生成的异常类

通过SQS客户端的exceptions属性可以拿到动态生成的异常类:

import boto3

sqs = boto3.resource('sqs', region_name='us-west-2')
queue = sqs.get_queue_by_name(QueueName='your-queue-name')
# 获取SQS客户端实例
sqs_client = sqs.meta.client
# 从客户端的exceptions中获取目标异常类
BatchEntryIdsNotDistinct = sqs_client.exceptions.BatchEntryIdsNotDistinct

try:
    queue.delete_messages(Entries=your_delete_entries)
except BatchEntryIdsNotDistinct as e:
    # 处理重复ID的逻辑
    print(f"重复ID错误:{e}")

注意事项

  • 动态生成的异常类名称可能因服务版本略有差异,优先推荐方式一,避免版本兼容问题。
  • 确保Entries列表中的每个条目Id字段都是唯一的,这是触发该异常的根本原因,提前校验可以避免异常发生。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:27:36