Matheus
03/07/2025, 3:39 PMfrom prefect import flow, task
@task
def task1():
raise ValueError("oh no!")
@task
def task2():
print('Test')
@flow
def my_flow():
task1.on_failure(task2())
state = my_flow(return_state=True)
result = state.result(raise_on_failure=False)
print(result)
Marvin
03/07/2025, 3:40 PMon_failure
callback in Prefect 2.x isn't correct. Prefect 2.x doesn't support directly attaching an on_failure
callback to a task in the way you've shown. Instead, you can use state change hooks at the flow level.
Here's a more appropriate way to implement an on_failure
hook using state change hooks in Prefect 2.x:
python
from prefect import flow, task
from prefect.states import Failed
@task
def task1():
raise ValueError("oh no!")
@task
def task2():
print('Task2 executed due to failure.')
def on_failure_callback(flow, flow_run, state):
if state.is_failed():
task2()
@flow
def my_flow():
task1()
if __name__ == "__main__":
my_flow().state.add_state_handler(on_failure_callback)
In this example, on_failure_callback
is defined to execute task2
when the flow enters a failed state. You can find more about state change hooks in the Prefect documentation.Matheus
03/07/2025, 3:51 PMMarvin
03/07/2025, 3:51 PMon_failure
method or attribute for tasks in Prefect 2.x. However, Prefect does support state change hooks and notifications, which can be configured to respond to task or flow failures. It seems that the on_failure
you're referring to might be part of a different mechanism or a misunderstanding.
If you have seen on_failure
used in Prefect 2.x elsewhere, it might be a custom implementation or part of a community extension. For built-in functionality, using state change hooks or Prefect's notification system is the recommended approach.
For more details on state change hooks, you can refer to the Prefect documentation on state change hooks. If you have a specific example or context where you've seen on_failure
, feel free to share it for further clarification.