diff options
| author | 2021-01-22 10:07:14 +0000 | |
|---|---|---|
| committer | 2021-01-22 10:07:14 +0000 | |
| commit | 2a31892f2339848e13f3e04fce37e64f5242ab84 (patch) | |
| tree | d4bd880cf1bb65314f6c46d3deb5e157dc150553 /bot/utils/scheduling.py | |
| parent | Merge pull request #1376 from python-discord/update-badges (diff) | |
| parent | Merge branch 'master' into bug/help/1341/race-conditions (diff) | |
Merge pull request #1346 from python-discord/bug/help/1341/race-conditions
Diffstat (limited to '')
| -rw-r--r-- | bot/utils/scheduling.py | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/bot/utils/scheduling.py b/bot/utils/scheduling.py index 03f31d78f..4dd036e4f 100644 --- a/bot/utils/scheduling.py +++ b/bot/utils/scheduling.py @@ -155,3 +155,20 @@ class Scheduler: # Log the exception if one exists. if exception: self._log.error(f"Error in task #{task_id} {id(done_task)}!", exc_info=exception) + + +def create_task(*args, **kwargs) -> asyncio.Task: + """Wrapper for `asyncio.create_task` which logs exceptions raised in the task.""" + task = asyncio.create_task(*args, **kwargs) + task.add_done_callback(_log_task_exception) + return task + + +def _log_task_exception(task: asyncio.Task) -> None: + """Retrieve and log the exception raised in `task` if one exists.""" + with contextlib.suppress(asyncio.CancelledError): + exception = task.exception() + # Log the exception if one exists. + if exception: + log = logging.getLogger(__name__) + log.error(f"Error in task {task.get_name()} {id(task)}!", exc_info=exception) |