Skip to content

Commit

Permalink
Merge pull request #2 from anexia/ANXOS-265
Browse files Browse the repository at this point in the history
ANXOS-265: Catch error on task process
  • Loading branch information
nezhar authored May 4, 2023
2 parents 21a336b + d6c13c0 commit 19d2660
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 18 deletions.
33 changes: 17 additions & 16 deletions django_future_tasks/management/commands/process_future_tasks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import logging
import signal
import sys
import time
import traceback
from sys import intern

from django import db
Expand Down Expand Up @@ -39,21 +41,8 @@ def tasks_for_processing():
)

@staticmethod
def process_task(task):
results = future_task_signal.send(sender=intern(task.type), instance=task)
for receiver, response in results:
if isinstance(response, Exception):
logger.exception(
"Exception occurred while processing task {} of type {}".format(
task.id, task.type
)
)
task.status = FutureTask.FUTURE_TASK_STATUS_ERROR
task.result = {
"error": str(response),
}
return False
return True
def _convert_exception_args(args):
return [str(arg) for arg in args]

def handle_tick(self):
task_list = self.tasks_for_processing()
Expand All @@ -62,8 +51,20 @@ def handle_tick(self):
for task in task_list:
task.status = FutureTask.FUTURE_TASK_STATUS_IN_PROGRESS
task.save()
if self.process_task(task):
try:
future_task_signal.send(sender=intern(task.type), instance=task)
task.status = FutureTask.FUTURE_TASK_STATUS_DONE
except Exception as exc:
task.status = FutureTask.FUTURE_TASK_STATUS_ERROR
task.result = {
"exception": "An exception of type {0} occurred.".format(
type(exc).__name__
),
"args": self._convert_exception_args(exc.args),
"traceback": traceback.format_exception(
*sys.exc_info(), limit=None, chain=None
),
}
task.save()

time.sleep(self.tick)
Expand Down
2 changes: 1 addition & 1 deletion tests/testapp/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ def my_task_function2(sender, instance, **kwargs):

@receiver(future_task_signal, sender=intern(settings.FUTURE_TASK_TYPE_ERROR))
def my_task_function_error(sender, instance, **kwargs):
return Exception("task error")
raise Exception("task error")
2 changes: 1 addition & 1 deletion tests/testapp/tests/test_future_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ def test_future_task_process_error(self):
call_command("process_future_tasks", onetimerun=True)
task = FutureTask.objects.get(pk=self.task_error.pk)
self.assertEqual(task.status, FutureTask.FUTURE_TASK_STATUS_ERROR)
self.assertEqual(task.result, {"error": "task error"})
self.assertEqual(task.result["args"], ["task error"])

0 comments on commit 19d2660

Please sign in to comment.