在python 3.11中,使用 exceptiongroup 处理并发异常的核心做法是:利用 asyncio.gather() 的 return_exceptions=true 参数收集所有任务结果,随后通过 anyio.exceptiongroup(或标准库 baseexceptiongroup)将多个异常打包为一个组对象抛出。开发者只需遍历该组对象,根据异常类型进行针对性清理或重试,从而避免单个异常导致整个并发流程中断。

asyncio.gather() 如何收集并抛出异常组
当调用 asyncio.gather() 时,若设置 return_exceptions=True,函数不会立即因第一个错误而停止,而是等待所有协程结束,并将成功结果和异常对象混合在一个列表中返回。如果列表中包含至少一个异常,且未手动处理,通常需要在业务逻辑层显式构造 ExceptionGroup 来统一抛出,或者依赖更高级的并发库自动包装。这种机制允许主线程一次性获取所有失败原因,便于批量恢复。

import asyncio
from exceptiongroup import ExceptionGroup
async def task_a():
raise ValueError("Task A failed")
async def task_b():
return "Success"
async def main():
# 1. 收集所有结果,包括异常
results = await asyncio.gather(
task_a(),
task_b(),
return_exceptions=True
)
# 2. 检查是否有异常
exceptions = [r for r in results if isinstance(r, BaseException)]
if exceptions:
# 3. 构造并抛出 ExceptionGroup
raise ExceptionGroup("Concurrent failures", exceptions)
try:
asyncio.run(main())
except ExceptionGroup as eg:
print(f"Caught group: {eg}")
for exc in eg.exceptions:
print(f"Individual: {exc}")
运行上述代码,预期输出为:Caught group: 2 sub-exceptionsIndividual: Task A failed
这里的关键在于 results 列表的结构。它保持了输入任务的顺序,因此可以通过索引定位哪个任务失败了。当存在多个不同类型的异常时,ExceptionGroup 能够保留它们的原始堆栈信息,这对于调试并发环境下的复杂问题至关重要。
如何解包并分类处理 ExceptionGroup
接收到 ExceptionGroup 后,直接捕获最外层的组往往不够,因为组内可能嵌套了其他类型的异常。最佳实践是使用 .split() 方法或迭代 .exceptions 属性,将异常按类型拆解。例如,可以将网络超时异常与数据解析异常分开处理:前者触发重试,后者记录日志并丢弃。这种分类处理确保了系统在面对部分失败时仍能保持部分功能可用。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
from exceptiongroup import ExceptionGroup
async def network_task():
raise TimeoutError("Network timeout")
async def parse_task():
raise JSONDecodeError("Invalid JSON", "", 0)
async def main():
results = await asyncio.gather(
network_task(),
parse_task(),
return_exceptions=True
)
exceptions = [r for r in results if isinstance(r, BaseException)]
if exceptions:
raise ExceptionGroup("Mixed errors", exceptions)
try:
asyncio.run(main())
except ExceptionGroup as eg:
# 尝试分离特定类型的异常
net_excs, remaining = eg.split(TimeoutError)
parse_excs, remaining = remaining.split(JSONDecodeError) if remaining else (None, None)
if net_excs:
print(f"Retrying {len(net_excs)} network tasks...")
if parse_excs:
print(f"Logging {len(parse_excs)} parse errors...")
if remaining:
print(f"Unhandled exceptions: {remaining}")
此段代码展示了 split 方法的用法。它将原异常组中的指定类型异常提取出来,返回一个新的异常组和剩余的异常组。如果指定的类型不存在,则返回空组和原组。这种方式比逐个 isinstance 判断更高效且语义清晰。注意,JSONDecodeError 在此处作为示例,实际使用时需确保已导入相应模块。
当 ExceptionGroup 包含嵌套组时如何处理
在某些复杂的并发场景中,异常组内部可能还包含其他的异常组,形成嵌套结构。这种情况通常发生在子任务本身也使用了 gather 或类似机制时。处理嵌套组需要递归地遍历 .exceptions,直到所有层级都被扁平化或分类。如果不处理嵌套,可能会导致某些深层异常被忽略,从而引发潜在的资源泄漏或状态不一致。
import asyncio
from exceptiongroup import ExceptionGroup
async def inner_task():
raise RuntimeError("Inner error")
async def outer_task():
try:
await inner_task()
except Exception as e:
# 模拟内部再次打包
raise ExceptionGroup("Inner Group", [e])
async def main():
results = await asyncio.gather(
outer_task(),
return_exceptions=True
)
exceptions = [r for r in results if isinstance(r, BaseException)]
if exceptions:
raise ExceptionGroup("Outer Group", exceptions)
try:
asyncio.run(main())
except ExceptionGroup as eg:
# 递归打印所有异常
def flatten(group):
for exc in group.exceptions:
if isinstance(exc, ExceptionGroup):
flatten(exc)
else:
print(f"Flattened: {exc}")
flatten(eg)
运行结果将显示 Flattened: Inner error。这表明通过递归遍历,我们成功穿透了嵌套的异常组,获取到了最底层的根本原因。在实际开发中,可以结合日志框架,将这种扁平化的异常链记录下来,以便后续分析。对于生产环境,建议封装一个通用的异常处理器,自动完成这种扁平化和分类操作,减少重复代码。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










