python-3.x 故意引发异常并使DAG失败

y1aodyip  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(143)

在我的Airflow dag中,我正在这样做:

try:
                        response = requests.get(url, params=params, headers=headers)
                        if response.status_code == 403:
                            raise Exception(f"Data Unavailable for metric: {m}, account: {account}")                          
                    except Exception as e:
                        logging.info(f"Exception during API request: {e} for metric: {m}, account: {account}")

except Exception as e:部分仅在API出错时运行,例如错误的API等。然而,在if response.status_code == 403的情况下,DAG不会失败,即使我手动编写了“raise Exception”。它只是移动到下一个步骤,并显示绿色或“成功”的任务。
如何强制DAG失败、抛出错误并在发生此错误时停止?

zfciruhq

zfciruhq1#

“except Exception as e:“在你引发异常之后出现,所以它会捕获它,并且在任务中实际上没有引发异常。还要注意,在Exception部分的日志记录之后,不会引发异常,因为它会吞下异常。

try:
        response = requests.get(url, params=params, headers=headers)
        response.raise_for_status()
   except HTTPError as e:
       if e.response.status_code == 403:
           raise Exception(f"Data Unavailable for metric: {m}, account: {account}")
   except Exception as e:
       logging.info(f"Exception during API request: {e} for metric: {m}, account: {account}")
       raise e

相关问题