Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 817e333

Browse files
committed
Starter for except*
1 parent fa49ef6 commit 817e333

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import asyncio
2+
import random
3+
4+
from asyncio import TaskGroup
5+
from typing import Any
6+
7+
8+
# region Async methods for logging
9+
10+
async def record_action_to_db():
11+
print("Logging to DB...")
12+
# noinspection PyTypeChecker
13+
outcomes: list[Any] = [None] * 3 + [DbException] * 2 + [SocketException]
14+
15+
if error := random.choice(outcomes):
16+
raise error("No can DB!")
17+
18+
print("Logged to DB successfully.")
19+
20+
21+
async def record_action_to_external_api():
22+
print("Logging to API...")
23+
# noinspection PyTypeChecker
24+
outcomes: list[Any] = [None] * 2 + [HttpException] * 3
25+
26+
if error := random.choice(outcomes):
27+
raise error("No can API!")
28+
29+
print("Logged to API successfully.")
30+
31+
32+
async def record_action_to_log():
33+
print("Logging to File...")
34+
# noinspection PyTypeChecker
35+
outcomes: list[Any] = [None] * 3 + [FileException] * 2
36+
37+
if error := random.choice(outcomes):
38+
raise error("No can File!")
39+
40+
print("Logged to File successfully.")
41+
42+
43+
# endregion
44+
45+
# region Local exception types
46+
class DbException(Exception):
47+
...
48+
49+
50+
class HttpException(Exception):
51+
...
52+
53+
54+
class SocketException(Exception):
55+
...
56+
57+
58+
class FileException(Exception):
59+
...
60+
61+
62+
# endregion
63+
64+
65+
def main():
66+
try:
67+
asyncio.run(record_action())
68+
except Exception as x:
69+
print("Error:")
70+
print(x)
71+
72+
73+
async def record_action():
74+
async with TaskGroup() as tg:
75+
tg.create_task(record_action_to_external_api())
76+
tg.create_task(record_action_to_log())
77+
tg.create_task(record_action_to_db())
78+
79+
80+
if __name__ == '__main__':
81+
main()

0 commit comments

Comments
 (0)