<@ULVA73B9P> Is there a way to define on_failure h...
# ask-marvin
y
@Marvin Is there a way to define on_failure hook but not in the @Flow line. Instead define it inside a global function?
m
Yes, there is a way to define an
on_failure
hook outside of the
@flow
decorator in Prefect. You can utilize the
with_options
method to configure the
on_failure
hook dynamically. Here is an example:
Copy code
python
from prefect import flow, get_run_logger
from prefect.deployments import Deployment

def err1(flow, flow_run, state):
    print("Preset on_failure hook")

def err2(flow, flow_run, state):
    print("Overwritten on_failure hook")

@flow(on_failure=[err1], name="initial_flow")
def demo_flow():
    logger = get_run_logger()
    <http://logger.info|logger.info>("Flow ran.")
    raise ValueError("An error occurred")

if __name__ == "__main__":
    dynamic_flow = demo_flow.with_options(on_failure=[err2], name="dynamic_flow")
    Deployment.build_from_flow(flow=dynamic_flow, name="test_deployment", apply=True)
In this example,
err1
is defined in the
@flow
decorator but can be overwritten by
err2
using
with_options
. For more information, you can refer to these links: - State Change Hooks - GitHub Issue on `with_options`