Skip to content

Commit f5949a2

Browse files
committed
Adding notes demo code.
1 parent b92db56 commit f5949a2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

code/ch02-error-messages/notes.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import sys
2+
from typing import Optional
3+
4+
5+
class DbException(Exception):
6+
pass
7+
8+
9+
class DbConnectionException(DbException):
10+
pass
11+
12+
13+
def connect_to_db(conn_str, server: Optional[str] = None, port: Optional[int] = None):
14+
if "server=" in conn_str or "port=" in conn_str:
15+
raise DbConnectionException("Connection string is malformed")
16+
17+
conn_str += f"&server={server}&port={port}"
18+
19+
print(f"Connecting to DB with {conn_str}")
20+
21+
22+
def setup_app():
23+
# conn_str = "mongo://user=mk&password=a&database=talkpython"
24+
conn_str = "mongo://user=mk&password=a&database=talkpython&port=1000"
25+
server = "localhost"
26+
port = 27017
27+
28+
try:
29+
connect_to_db(conn_str, server, port)
30+
except DbException as dbe:
31+
dbe.add_note("Cannot specify server or port explicitly and include it in the connection string.")
32+
dbe.add_note("Amend the connection string and try again.")
33+
raise
34+
35+
36+
def main():
37+
# You'll see the notes here
38+
# setup_app()
39+
40+
try:
41+
setup_app()
42+
print("App ready")
43+
except Exception as x:
44+
print("Error starting app:")
45+
print(f'{type(x).__name__}: {x}')
46+
for n in x.__notes__:
47+
print(f"NOTE: {n}")
48+
49+
sys.exit(7)
50+
51+
52+
if __name__ == '__main__':
53+
main()

0 commit comments

Comments
 (0)