在python中正确捕获并处理asyncio任务抛出的异常,核心做法是使用`asyncio.gather()`配合`return_exceptions=true`参数,或者使用`try...except`块包裹具体的协程调用。当使用`gather`时,如果未设置`return_exceptions=true`,第一个异常会立即取消其他并发任务;若设置了该参数,所有任务的异常都会被收集到一个结果列表中,允许程序继续执行并统一处理错误。对于单个任务,直接在其定义或调用处使用标准的异步异常处理机制即可。

asyncio.gather默认行为下异常如何传播
当不指定return_exceptions=True时,asyncio.gather遵循“快速失败”原则。一旦其中一个协程抛出异常,该异常会立即被抛出到gather的调用者,同时其他正在运行的任务会被自动取消。这意味着你无法获取其他成功完成任务的结果,只能处理那个最先发生的异常。这种模式适用于任何子任务失败都导致整体操作无效的场景。

import asyncio
async def task_with_error(name):
if name == "bad":
raise ValueError(f"{name} failed")
return f"{name} success"
async def main():
try:
# 默认行为:任一异常触发即停止并传播
results = await asyncio.gather(
task_with_error("good"),
task_with_error("bad"),
task_with_error("also_good")
)
print(results)
except Exception as e:
print(f"Caught exception: {e}")
asyncio.run(main())
运行上述代码将输出:Caught exception: bad failed。
注意,good和also_good的结果不会出现在results中,因为异常抛出后流程已中断。
return_exceptions=True模式下异常如何被收集
通过设置return_exceptions=True,asyncio.gather会将所有协程的运行结果(包括异常实例)全部返回到一个列表中,而不会提前取消其他任务。这使得你可以遍历结果列表,区分哪些是正常返回值,哪些是异常对象,从而进行细粒度的错误恢复或日志记录。这是处理批量异步请求(如HTTP并发抓取)时的推荐做法,因为单个请求失败不应阻塞整个批次的完成。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
async def task_with_error(name):
if name == "bad":
raise ValueError(f"{name} failed")
return f"{name} success"
async def main():
# 设置 return_exceptions=True
results = await asyncio.gather(
task_with_error("good"),
task_with_error("bad"),
task_with_error("also_good"),
return_exceptions=True
)
for i, res in enumerate(results):
if isinstance(res, Exception):
print(f"Task {i} failed with: {res}")
else:
print(f"Task {i} succeeded with: {res}")
asyncio.run(main())
运行上述代码将输出:Task 0 succeeded with: good successTask 1 failed with: bad failedTask 2 succeeded with: also_good success。
可以看到,即使中间的任务失败了,后续任务依然执行完毕,且所有结果都被完整收集。
单个asyncio.Task对象中异常的具体捕获方式
当你直接创建并管理asyncio.Task对象时,异常不会自动抛出,除非你显式地调用task.result()或await task。如果在创建任务后没有立即等待它,而是先做其他事情,那么异常会被存储在任务内部,直到你尝试获取其结果时才重新抛出。这种机制允许你在任务完成后检查其状态,并在需要时统一处理错误,而不是在任务执行的瞬间就中断主逻辑。
import asyncio
async def failing_task():
await asyncio.sleep(1)
raise RuntimeError("Task crashed")
async def main():
task = asyncio.create_task(failing_task())
# 做一些其他工作...
await asyncio.sleep(0.5)
try:
# 这里才会真正触发异常
await task
except RuntimeError as e:
print(f"Handled task error: {e}")
asyncio.run(main())
此示例展示了create_task创建的后台任务,其异常在await时刻才被捕获。这确保了主流程可以在任务执行期间继续运行,仅在需要结果或确认完成时才处理潜在的错误。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










