def handle_exception(task: asyncio.Task) -> None: """Handle any exceptions that occur in tasks. Log all errors and stop the event loop when any exception other than asyncio.CancelledError is raised. Args: task: The task that raised the exception. """ try: task.result() except asyncio.CancelledError: pass except Exception as e: if logging.getLogger().level <= logging.DEBUG: logging.exception("Exception raised by task %s", task.get_name()) else: logging.error("%s", e) context_loop = asyncio.get_event_loop() task_loop = task.get_loop() if task_loop is not context_loop: task_loop.stop()
def get_asyncio_future_event_loop(task: asyncio.Task): if hasattr(task, "get_loop"): return task.get_loop() else: return task._loop