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

Telegram机器人保质期校验函数逻辑异常:正确日期仍触发错误

日期校验逻辑错误导致消息处理器异常触发

问题场景

现有一段Telegram机器人代码,本意是仅在用户输入错误日期时触发check_shelf_life发送错误提示,但实际输入正确日期时也会弹出错误;交换校验函数的返回值后,又出现正确、错误日期都不触发错误提示的问题。

原代码

def is_valid_shelf_life(date):
    try:
        shelf_life = datetime.strptime(date, "%d.%m.%y")
    except(TypeError, ValueError):
        return True
    return False


@db.message_handler(is_valid_shelf_life, state=ProductAddingStatesGroup.shelf_life)
async def check_shelf_life(message: types.Message):
    await message.answer("Дата введена не корректно!")

问题原因

你的校验函数返回逻辑完全搞反了当前框架的规则:

  • 框架中message_handler的校验函数,返回True表示输入符合要求(跳过错误处理器),返回False表示输入不符合要求(触发错误处理器)
  • 原代码中,正确日期解析成功后返回False,被框架判定为输入无效,触发了错误提示
  • 错误日期捕获异常后返回True,被框架判定为输入有效,跳过了错误提示
  • 交换返回值后,错误逻辑虽被修正,但正确日期返回False仍会触发错误提示,最终导致你误以为“正确与错误数据均能通过校验”

修正后的代码

def is_valid_shelf_life(date):
    try:
        # 尝试按「日.月.年(两位年份)」格式解析日期
        shelf_life = datetime.strptime(date, "%d.%m.%y")
    except (TypeError, ValueError):
        # 解析失败,日期格式错误,返回False触发错误处理
        return False
    # 解析成功,日期格式正确,返回True跳过错误处理
    return True


@db.message_handler(is_valid_shelf_life, state=ProductAddingStatesGroup.shelf_life)
async def check_shelf_life(message: types.Message):
    await message.answer("Дата введена не корректно!")

说明

修正后,当用户输入不符合日.月.年格式的日期时,校验函数返回False,触发check_shelf_life发送错误提示;输入正确格式的日期时,校验函数返回True,框架会跳过该错误处理器,继续执行后续正常流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:20:39