Skip to content

Commit

Permalink
Add custom error raising for connection errors
Browse files Browse the repository at this point in the history
  • Loading branch information
gideonshaked committed Jul 23, 2021
1 parent c93670a commit b695eaa
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/client/send_data.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__all__ = ["send"]
__all__ = ["send", "ConnectionError"]

import json
import socket
Expand All @@ -11,5 +11,20 @@ def send(data: dict) -> None:
serialized_data = json.dumps(data)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(SERVER_ADDRESS)
sock.sendall(bytes(serialized_data + "\n", "utf-8"))
try:
sock.connect(SERVER_ADDRESS)
except socket.gaierror as e:
raise ConnectionError(
f'Address-related error connecting to server.\nCheck server is on and running.\n\nLib says: "{e.__class__.__module__}.{e.__class__.__qualname__}: {e}"'
)
except socket.error as e:
raise ConnectionError(
f'General connection error.\nCheck server is on and running.\n\nLib says: "{e.__class__.__module__}.{e.__class__.__qualname__}: {e}"'
)
else:
sock.sendall(bytes(serialized_data + "\n", "utf-8"))


class ConnectionError(Exception):
def __init__(self, message: str):
self.message = message

0 comments on commit b695eaa

Please sign in to comment.