python - 在异步收集中捕获异常

标签 python asynchronous exception async-await

假设有几个我们发送到事件循环的协程

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/

相关文章:

python - 使用 Python/FFMPEG/Pydub 将 Wave 文件的部分静音

ios - 异步操作未按顺序完成

php - 异步子进程中的 Symfony2 命令

c# - 如何在基于异步/等待的单线程协程实现中捕获异常

android - gradle项目中输入流不能为空异常

python - pygame中的显示闪烁(如何使我的代码更高效)

python - 有没有python模块,可以把地理坐标转成对应城市的名字?

Python strip() 多个字符?

java - hibernate/ Spring 3 : could not initialize proxy - no Session

python - 如何在异常处理中获取python默认的异常消息