Can I add an on_failure callback to a celery task created with the task decorator?

Here is a full solution (works for Celery 4+):

import celery
from celery.task import task

class MyBaseClassForTask(celery.Task):

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        # exc (Exception) - The exception raised by the task.
        # args (Tuple) - Original arguments for the task that failed.
        # kwargs (Dict) - Original keyword arguments for the task that failed.
        print('{0!r} failed: {1!r}'.format(task_id, exc))

@task(name="foo:my_task", base=MyBaseClassForTask)
def add(x, y):
    raise KeyError()

Resources:

  • http://docs.celeryproject.org/en/latest/userguide/tasks.html#task-inheritance
  • http://docs.celeryproject.org/en/latest/reference/celery.app.task.html#celery.app.task.Task.on_failure
  • http://docs.celeryproject.org/en/latest/userguide/tasks.html#abstract-classes

You can provide the function directly to the decorator:

def fun(self, exc, task_id, args, kwargs, einfo):
    print('Failed!')

@task(name="foo:my_task", on_failure=fun)
def add(x, y):
    raise KeyError()

Tags:

Celery