在python异步体系中,未捕获的全局异常通常由事件循环的默认异常处理机制接管。要正确处理这类异常,最直接的办法是调用 loop.set_exception_handler() 注册自定义处理器,或者使用 asyncio.run() 时利用其内置的日志记录功能。这样做可以防止程序因未处理的异常而静默崩溃或产生难以追踪的日志缺失。

如何拦截并记录 asyncio 中的未处理异常
通过重写事件循环的 exception_handler 方法,可以捕获所有未被任务内部 try...except 块处理的异常。这允许你在异常发生时执行特定的清理操作或发送告警通知,而不是仅仅依赖默认的 stderr 输出。

import asyncio
class CustomLoop(asyncio.SelectorEventLoop):
def exception_handler(self, loop, context):
print(f"Custom Handler: {context.get('message')}")
if 'exception' in context:
print(f"Exception details: {context['exception']}")
loop = CustomLoop()
asyncio.set_event_loop(loop)
async def failing_task():
raise ValueError("Something went wrong")
loop.create_task(failing_task())
try:
loop.run_forever()
finally:
loop.close()运行上述代码将触发 CustomLoop 中的 exception_handler,打印出自定义消息和具体的异常对象。这种方式适用于需要长期运行的服务,确保所有异常都被显式记录。
立即学习“Python免费学习笔记(深入)”;
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
如何在 asyncio.run 中配置全局异常行为
对于现代 Python 应用,推荐使用 asyncio.run() 作为入口点。虽然它不直接支持自定义 exception_handler 的注入,但可以通过设置 asyncio.get_event_loop_policy() 来间接控制。此外,结合 logging 模块可以更优雅地处理这些异常,避免污染控制台输出。

import asyncio
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
async def task_with_error():
await asyncio.sleep(1)
raise RuntimeError("Critical failure")
async def main():
try:
await task_with_error()
except Exception as e:
logger.error(f"Unhandled error in main: {e}", exc_info=True)
if __name__ == "__main__":
asyncio.run(main())在这个示例中,main 函数捕获了 task_with_error 抛出的异常,并通过 logger 进行记录。这种方法确保了异常信息被结构化地保存,便于后续分析。如果希望完全自动化,可以在 main 外部包裹一个通用的异常捕获逻辑,或者使用第三方库如 sentry-sdk 来集成错误追踪。
当协程内部抛出异常但未 await 时会发生什么
如果在创建任务后没有立即 await 或 gather 它,且该任务内部抛出异常,异常将被挂起直到任务被等待。如果任务从未被等待,异常可能永远不会被触发,导致资源泄漏或状态不一致。因此,始终确保任务的生命周期被正确管理是关键。

















