无法在Django中捕获Celery操作错误

时间:2018-04-18 08:17:56

标签: django celery

我有以下代码:

def save()
   super().save(*args, **kwargs)
   try:
       transaction.on_commit(lambda: c_task.delay(a, b, self.pk))
   except Exception as e:
       print(e)

@app.task(bind=True, name='c_task', max_retries=4, soft_time_limit_exception=300)
def c_task(self, a, b, i):

    from .models import ModelA

    try:
        json_data = entity(a,b,i, const)
        .....
    except Exception as e:

        raise self.retry(exc=e, countdown=exponential_backoff(self))

如果Redis服务器出现故障,我会收到和ErrorError。我尝试使用Celery OperationalError或一般异常来捕获它。

该行仍在执行并抛出错误。如果Redis失败了,我不希望一切都失败,因为我的代码有一个“解决方法”,但我无法发现错误。

回溯:

 transaction.on_commit(lambda: c_task.delay(a, b, self.pk))

\lib\site-packages\celery\app\task.py in delay

            return self.apply_async(args, kwargs)

lib\site-packages\celery\app\task.py in apply_async

                **options

\lib\site-packages\celery\app\base.py in send_task

                    amqp.send_task_message(P, name, message, **options)

\lib\contextlib.py in __exit__

                    self.gen.throw(type, value, traceback)

\lib\site-packages\kombu\connection.py in _reraise_as_library_errors

                        sys.exc_info()[2])

\lib\site-packages\vine\five.py in reraise

                raise value.with_traceback(tb)

\lib\site-packages\kombu\connection.py in _reraise_as_library_errors

                yield
\lib\site-packages\celery\app\base.py in send_task

                    self.backend.on_task_call(P, task_id)
\lib\site-packages\celery\backends\redis.py in on_task_call

                self.result_consumer.consume_from(task_id)

\lib\site-packages\celery\backends\redis.py in consume_from

                return self.start(task_id)

 \lib\site-packages\celery\backends\redis.py in start

            self._consume_from(initial_task_id)

\lib\site-packages\celery\backends\redis.py in _consume_from

                self._pubsub.subscribe(key)
\lib\site-packages\redis\client.py in subscribe

            ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))

 \lib\site-packages\redis\client.py in execute_command

            self._execute(connection, connection.send_command, *args)

\lib\site-packages\redis\client.py in _execute

                connection.connect()

d\lib\site-packages\redis\connection.py in connect

                raise ConnectionError(self._error_message(e))

1 个答案:

答案 0 :(得分:4)

您需要在下方更改

transaction.on_commit(lambda: c_task.delay(a, b, self.pk))

def run_task(a, b, pk):
   try:
      c_task.delay(a, b, pk)
   except Exception as ex:
      print(ex)
transaction.on_commit(lambda: run_task(a, b, self.pk))

这将确保处理连接异常