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

如何在数据库插入函数报错时退出调用函数且不终止Cron任务

解决方案:通过异常传递终止当前函数而非整个进程

你需要放弃使用exit()(它会终止整个Python进程),转而通过抛出并传递异常来实现仅终止second函数的执行,同时保留Telegram机器人和Cron任务的整体运行。

步骤1:修改数据库插入函数,抛出异常而非终止进程

让insert_link_into_bd在捕获到目标错误时抛出异常,将错误处理的控制权交还给调用它的second函数:

import mysql.connector

# 可选:自定义异常,让错误逻辑更清晰
class DuplicateEntryError(Exception):
    pass

def insert_link_into_bd(category, title, link, author, author_link, finally_text, date):
    cursor = db.cursor(buffered=True)
    try:
        syntext = """Insert into links (Category,Title,Article_link,Author,Author_link,Text, DATE) values (%s,%s,%s,%s,%s,%s,%s);"""
        value = (category, title, link, author, author_link, finally_text, date)
        cursor.execute(syntext, value)
        db.commit()
    except mysql.connector.Error as err:
        print(err.sqlstate)
        if err.sqlstate == '23000':
            # 抛出自定义异常,传递错误信息
            raise DuplicateEntryError("数据库存在重复条目") from err
        # 其他类型的错误可根据需求选择抛出或处理

步骤2:在调用函数中处理异常,终止当前流程

在second函数中,通过捕获异常来终止自身执行,不会影响整个程序的运行:

def second():
    # 前置操作
    try:
        insert_link_into_bd(category, title, link, author, author_link, finally_text, date)
        # 如果插入成功,继续执行后续代码
        # ... 其他业务逻辑 ...
    except DuplicateEntryError:
        # 捕获到重复条目错误,直接返回终止当前函数
        return
    # 非错误场景下的后续代码

核心逻辑说明

  • exit()/sys.exit()会直接终止整个Python解释器进程,导致Telegram机器人、Cron任务等所有关联代码停止运行,这是你需要避免的。
  • 抛出异常只会中断当前函数的执行流程:insert_link_into_bd抛出异常后,second函数会立即跳转到异常捕获块并返回,不会执行后续代码,但整个程序的其他部分(如机器人的消息监听、Cron的其他任务)仍会正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:17:06