【问题标题】:Exception from a prefect task cannot be caught by sys.excepthook来自完美任务的异常不能被 sys.excepthook 捕获
【发布时间】:2022-01-22 12:22:19
【问题描述】:

我为sys.excepthook设置了一个异常处理程序:

    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            logger.error("KeyboardInterrupt\n")
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return

        # Preserve the exception info in the log.
        print("UNEXPECTED ERROR OCCURRED!")
        logger.error(
            "Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)
        )

        # Send the exception info to Slack.
        exc_text = (
            f"[Error] *{logger_name}* <@U01HX7R5VPW>\n```"
            + "".join(format_exception(exc_type, exc_value, exc_traceback))
            + "```"
        )
        notify(exc_text, critical=True)
    sys.excepthook = handle_exception

我的流程运行如下:

with Flow("stocktwits-crawler", schedule=schedule) as f:
        print("Running...")
        if ...:
                a(...)
        else:
                b(...)
        logger.info("All finished.")

a()b() 方法已添加 @task 装饰器。

我的问题是:如果在a()b() 之外引发错误,我的异常处理程序可以捕获消息并写入日志文件。但是,当在完美任务(a()b())内部引发错误时,日志文件不输出任何内容,这意味着异常处理程序不会捕获错误消息。我不确定prefect task 是否有另一个用于异常处理程序的钩子。您能否给我一些关于如何进一步调试此问题的建议?

【问题讨论】:

    标签: python prefect


    【解决方案1】:

    一般来说,Prefect 管理您的流程和任务的状态,因此您不必构建自己的异常处理程序。您是否知道 Prefect 拥有开箱即用的 state handlers 提供此功能? Here 是一个通过 Slack 消息发送完整异常回溯的示例。

    此外,在 Prefect @task 装饰的单独功能。您可以将 if/else 语句替换为 conditional tasks,例如 case

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多