How to make a celery task fail from within the task without raising an exception?

3,986 views
Skip to first unread message

Stephan Meier

unread,
Oct 8, 2011, 4:03:12 PM10/8/11
to celery-users
Under some conditions, I want to make a celery task fail from within
that task without raising an exception.

However, it seems that the state can only be modified
( task_name.update_state(state=states.FAILURE) ) while the task is
running and once it is completed - celery changes the state to
whatever it deems is the outcome. Is there any way, without failing
the task by raising an exception, to make celery return that the task
has failed?

Thank you very much for your help.

Best regards,
Stephan

Ask Solem

unread,
Oct 10, 2011, 8:46:20 AM10/10/11
to celery...@googlegroups.com


You could set ignore_result=True, then it won't keep track of state.
You may want to keep the other states though, in that case you can
save the FAILURE state in the `after_return` handler:


class MyTask(Task):

def after_return(self, *args, **kwargs):
self.update_state(state=states.FAILURE)
super(MyTask, self).after_return(*args, **kwargs)


after_return will be called *after* any state has been updated
by the worker.

--
Ask Solem
twitter.com/asksol | +44 (0)7713357179

Stephan Meier

unread,
Oct 11, 2011, 3:18:44 AM10/11/11
to celery-users
Dear Ask Solem,
Thank you for your reply, especially the 'after_return' handler is an
interesting option and good to know for the future.

I solved the issue by simply returning a string 'FAILURE' and then
checking for that as follows:

result = AsyncResult(task_id)
if result.state == 'FAILURE' or (result.state == 'SUCCESS' and
result.get() == 'FAILURE'):
# Failure processing task
Reply all
Reply to author
Forward
0 new messages