mirror of
https://github.com/Xevion/tcp-chat.git
synced 2025-12-06 03:16:44 -06:00
improve logging/exceptions for data reception, new exceptions.py file
This commit is contained in:
5
exceptions.py
Normal file
5
exceptions.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
class TCPChatException(BaseException):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class DataReceptionException(TCPChatException):
|
||||||
|
pass
|
||||||
@@ -4,11 +4,13 @@ import random
|
|||||||
import socket
|
import socket
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from typing import Any, List
|
from json import JSONDecodeError
|
||||||
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
import constants
|
import constants
|
||||||
import helpers
|
import helpers
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
|
from exceptions import DataReceptionException
|
||||||
from server import db
|
from server import db
|
||||||
from server.commands import CommandHandler
|
from server.commands import CommandHandler
|
||||||
from server.db import Database
|
from server.db import Database
|
||||||
@@ -123,11 +125,21 @@ class Client(BaseClient):
|
|||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
def receive(self) -> Any:
|
def receive(self) -> Any:
|
||||||
length = int(self.conn.recv(constants.HEADER_LENGTH).decode('utf-8'))
|
try:
|
||||||
logger.debug(f'Header received - Length {length}')
|
length = int(self.conn.recv(constants.HEADER_LENGTH).decode('utf-8'))
|
||||||
data = json.loads(self.conn.recv(length).decode('utf-8'))
|
except ValueError:
|
||||||
logger.info(f'Data received/parsed, type: {data["type"]}')
|
raise DataReceptionException('The socket did not receive the expected header.')
|
||||||
return data
|
else:
|
||||||
|
logger.debug(f'Header received - Length {length}')
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = self.conn.recv(length).decode('utf-8')
|
||||||
|
data = json.loads(data)
|
||||||
|
except JSONDecodeError:
|
||||||
|
raise DataReceptionException('The socket received a invalid JSON structure.')
|
||||||
|
else:
|
||||||
|
logger.info(f'Data received/parsed, type: {data["type"]}')
|
||||||
|
return data
|
||||||
|
|
||||||
def handle_nickname(self, nickname: str) -> None:
|
def handle_nickname(self, nickname: str) -> None:
|
||||||
if self.last_nickname_change is None:
|
if self.last_nickname_change is None:
|
||||||
|
|||||||
Reference in New Issue
Block a user