https://prefect.io logo
Title
m

merlin

11/01/2022, 9:04 PM
How can I fail a task? I am try/catching exceptions, which works file, but I still want the task to fail. The docs didn't quite show this example:
@task
def fail_task():
    return Failed()

@flow
def fail_flow_i_hope():
    fail_task()

fail_flow_i_hope()

11:42:32.292 | DEBUG   | Task run 'always_fail_task-d83fd752-0' - Beginning execution...
11:42:32.302 | INFO    | Task run 'always_fail_task-d83fd752-0' - Finished in state Completed()
...
11:42:32.313 | INFO    | Flow run 'ludicrous-lemur' - Finished in state Completed('All states completed.')
I'd like a task to fail, and then do retries (or not) but end the steps in the flow, with the flow also failed.
1
m

Mason Menges

11/01/2022, 9:06 PM
In most cases like this it would make more sense to raise an exception within the task in scenarios where you want it to fail
@task
def fail_task():
    # you could really raise any exception here
    raise ValueError 

@flow
def fail_flow_i_hope():
    fail_task()

fail_flow_i_hope()
m

merlin

11/01/2022, 9:13 PM
So I can only fail a task by raising an exception? Its seems like my try/catch components aren't really needed in that case.
Oh, maybe I have it now. The following still raises a prefect exception. ``` @task def fail_task(): try: service_call(..etc) except CustomException: return Failed() @flow def fail_flow_i_hope(): fail_task(return_state=True) fail_flow_i_hope() 14:16:16.942 | DEBUG | Task run 'fail_task-d8c73196-0' - Beginning execution... 14:16:16.952 | ERROR | Task run 'fail_task-d8c73196-0' - Finished in state Failed() Traceback (most recent call last): ...etc... raise await get_state_exception(state) prefect.exceptions.FailedRun: None