如何在Lambda的Python代码中检查EventBridge调度是否存在?
检查EventBridge调度是否存在的Python实现
在Lambda中使用Python调用EventBridge的get_schedule接口时,若调度不存在会抛出异常中断代码,你可以通过捕获特定异常的方式优雅处理这个场景,避免代码中断。
实现代码示例
import boto3 from botocore.exceptions import ClientError def lambda_handler(event, context): client = boto3.client('scheduler') schedule_name = "Name of the schedule" try: response = client.get_schedule(Name=schedule_name) # 调度存在,执行后续逻辑 print(f"调度 {schedule_name} 存在,详情:{response}") return {"status": "exists", "details": response} except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': # 调度不存在的情况 print(f"调度 {schedule_name} 不存在") return {"status": "not_exists"} else: # 其他异常,比如权限问题等,重新抛出 raise
关键说明
- 捕获
botocore.exceptions.ClientError异常,这是boto3客户端操作失败时抛出的通用异常 - 通过判断异常中的
Error.Code是否为ResourceNotFoundException,精准识别调度不存在的场景 - 其他异常(如权限不足、参数错误等)重新抛出,避免隐藏其他问题
内容的提问来源于stack exchange,提问作者Ahmed Youniss
相关产品推荐
相关产品推荐

