improve logging/exceptions for data reception, new exceptions.py file

This commit is contained in:
Xevion
2021-01-22 09:39:16 -06:00
parent 12917edaa4
commit 53faae4154
2 changed files with 23 additions and 6 deletions

5
exceptions.py Normal file
View File

@@ -0,0 +1,5 @@
class TCPChatException(BaseException):
pass
class DataReceptionException(TCPChatException):
pass

View File

@@ -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,9 +125,19 @@ class Client(BaseClient):
cur.close() cur.close()
def receive(self) -> Any: def receive(self) -> Any:
try:
length = int(self.conn.recv(constants.HEADER_LENGTH).decode('utf-8')) length = int(self.conn.recv(constants.HEADER_LENGTH).decode('utf-8'))
except ValueError:
raise DataReceptionException('The socket did not receive the expected header.')
else:
logger.debug(f'Header received - Length {length}') logger.debug(f'Header received - Length {length}')
data = json.loads(self.conn.recv(length).decode('utf-8'))
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"]}') logger.info(f'Data received/parsed, type: {data["type"]}')
return data return data