How to make a celery task fail from within the task?

后端 未结 3 973
忘掉有多难
忘掉有多难 2021-02-05 00:37

Under some conditions, I want to make a celery task fail from within that task. I tried the following:

from celery.task import task
from celery import states

@t         


        
3条回答
  •  别跟我提以往
    2021-02-05 01:19

    I'd like to further expand on Pierre's answer as I've encountered some issues using the suggested solution.

    To allow custom fields when updating a task's state to states.FAILURE, it is important to also mock some attributes that a FAILURE state would have (notice exc_type and exc_message) While the solution will terminate the task, any attempt to query the state (For example - to fetch the 'REASON FOR FAILURE' value) will fail.

    Below is a snippet for reference I took from: https://www.distributedpython.com/2018/09/28/celery-task-states/

    @app.task(bind=True)
    def task(self):
        try:
            raise ValueError('Some error')
        except Exception as ex:
            self.update_state(
                state=states.FAILURE,
                meta={
                    'exc_type': type(ex).__name__,
                    'exc_message': traceback.format_exc().split('\n')
                    'custom': '...'
                })
            raise Ignore()
    

提交回复
热议问题