Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exception in asyncio gather

Suppose there are several coroutines that we send to the event loop

task_list = [task1(), task2(), task3()]
res = asyncio.gather(*task_list, return_exceptions=True)

Regarding documentation

If return_exceptions is True, exceptions are treated the same as successful results, and aggregated in the result list.

I.e. if for example task2 returns an error, the result will be

res = [task1_result, task2_error, task3_result]

The result is further processed in another process, and I would like to pass some default value if there is an error in the response. The question is how to check for an exception in the event_loop response. Smth like (warning pseudo code!)

response = default if any(res is Error) else res
like image 341
Jekson Avatar asked Sep 15 '25 14:09

Jekson


1 Answers

You could use map function to replace errors in result list by default value. For checking if result is an error isinstance(result, Exception) can be used. Like so:

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]
like image 135
alex_noname Avatar answered Sep 18 '25 10:09

alex_noname