Koen
03/19/2025, 10:42 AMMarvin
03/19/2025, 10:42 AMstate_handlerspython
from prefect import flow, task, State
# Define a state handler function
def on_failure(flow, state: State):
    if state.is_failed():
        # Add your custom action here
        print("Flow failed! Executing custom action.")
@flow(state_handlers=[on_failure])
def my_flow():
    # Define your tasks here
    pass
# Run the flow
my_flow()Koen
03/19/2025, 10:45 AMMarvin
03/19/2025, 10:46 AMCompletedpython
from prefect import flow, task, State
# Define a state handler function
def on_state_change(flow, state: State):
    if state.is_failed():
        # Action for failed state
        print("Flow failed! Executing custom action.")
    elif state.is_completed():
        # Action for completed state
        print("Flow completed successfully!")
@flow(state_handlers=[on_state_change])
def my_flow():
    # Define your tasks here
    pass
# Run the flow
my_flow()on_state_changeFailedCompletedKoen
03/19/2025, 10:51 AMMarvin
03/19/2025, 10:51 AMfrom prefect import flowflow@flowKoen
03/19/2025, 10:52 AMMarvin
03/19/2025, 10:52 AMstate_handlers@flowpython
from prefect import flow, task
def on_failure():
    # Custom action on failure
    print("Flow failed! Executing custom action.")
def on_success():
    # Custom action on success
    print("Flow completed successfully!")
@flow
def my_flow():
    try:
        # Your tasks here
        pass
    except Exception as e:
        on_failure()
        raise e
    else:
        on_success()
# Run the flow
my_flow()Koen
03/19/2025, 10:53 AMMarvin
03/19/2025, 10:53 AMpython
from prefect import task, flow
from prefect.states import State
# Define a state hook function
def on_task_failure(task, task_run, state: State):
    if state.is_failed():
        print(f"Task {task.name} failed! Executing custom action.")
@task(state_handlers=[on_task_failure])
def my_task():
    raise ValueError("This task is designed to fail.")
@flow
def my_flow():
    my_task()
# Run the flow
my_flow()on_task_failureFailedstate_handlersmy_flowmy_taskKoen
03/19/2025, 1:52 PMMarvin
03/19/2025, 1:52 PMFailedCompletedFailedFailedKoen
03/19/2025, 1:55 PMKoen
03/19/2025, 1:55 PMMarvin
03/19/2025, 1:55 PMFailedCompleted