假设有几个我们发送到事件循环的协程
task_list = [task1(), task2(), task3()]
res = asyncio.gather(*task_list, return_exceptions=True)
关于文档
If return_exceptions is True, exceptions are treated the same as successful results, and aggregated in the result list.
即例如,如果 task2 返回一个错误,结果将是
res = [task1_result, task2_error, task3_result]
结果在另一个进程中进一步处理,如果响应中有错误,我想传递一些默认值。问题是如何检查 event_loop 响应中的异常。像(警告伪代码!)
response = default if any(res is Error) else res
最佳答案
您可以使用map
函数将结果列表中的错误替换为默认值。要检查结果是否为错误,可以使用 isinstance(result, Exception)
。像这样:
task_list = [task1(), task2()]
res = await asyncio.gather(*task_list, return_exceptions=True) # res = ["result", ArithmeticError()]
res = list(map(lambda r: r if not isinstance(r, Exception) else default_value, res)) # res = ["result", None]
关于python - 在异步收集中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65579733/