Skip to content

Commit

Permalink
Improve exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
peprolinbot committed Aug 31, 2023
1 parent 509b88f commit 618fce4
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 14 deletions.
2 changes: 1 addition & 1 deletion busGal_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
from . import known_servers


__all__ = ["transport", "accounts"]
__all__ = ["transport", "accounts", "exceptions"]
71 changes: 67 additions & 4 deletions busGal_api/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,68 @@
class TPGalWSException(Exception):
pass
class AppError():
"""
Represents error information returned by the server
"""
def __init__(self, code, message):
self.code = code
"""
An integer which identifies an error
"""
self.message = message
"""
The actual error message
"""

class TPGalWSBlankResponse(Exception):
pass

class TPGalWSBaseResponseException(Exception):
"""
Exception used for succesful connections to the server but that for some reason didn't provide any result
"""

def __init__(self, message, response):

super().__init__(
f"HTTP --> {response.status_code}: {response.reason} || {message}")

self.response = response
"""
The `requests.response` object of the failed request
"""


class TPGalWSAppException(TPGalWSBaseResponseException):
"""
Exception used when the server returns a JSON response with information about an error
"""

def __init__(self, response, data_out=None):
self.data_out = data_out or response.json()
"""
`requests.response.json()`
"""

self.app_error = AppError(self.data_out.get(
'code'), self.data_out.get('message'))
"""
`AppError` with more information about the cause of the error
"""

super().__init__(
f"App --> {self.app_error.code}: {self.app_error.message}", response)


class TPGalWSBlankResponse(TPGalWSBaseResponseException):
"""
Exception used when the server returns nothing (really, just nothing, `b''` if you know what I mean😉)
"""

def __init__(self, response):
super().__init__("The API errored silently", response)


class TPGalWSBadJsonException(TPGalWSBaseResponseException):
"""
Exception when the server returns something, but it isn't JSON-parseable
"""

def __init__(self, response):
super().__init__("Bad JSON in response", response)
13 changes: 5 additions & 8 deletions busGal_api/rest_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from json import JSONDecodeError
import logging

from .exceptions import TPGalWSException, TPGalWSBlankResponse
from .exceptions import *


class RestAdapter():
Expand Down Expand Up @@ -56,16 +56,14 @@ def _escape_dict(data: dict) -> str:
method=http_method, url=full_url, headers=headers, params=ep_params, json=data)
except requests.exceptions.RequestException as e:
self._logger.error(msg=(str(e)))
raise TPGalWSException("Request failed") from e
raise e

try:
data_out = response.json()
except (ValueError, JSONDecodeError) as e:
if response.content == b'':
raise TPGalWSBlankResponse(
f"The API errored silently || HTTP {response.status_code}: {response.reason}") from e
raise TPGalWSException(
f"Bad JSON in response || HTTP {response.status_code}: {response.reason}") from e
raise TPGalWSBlankResponse(response) from e
raise TPGalWSBadJsonException(response) from e

is_success = 299 >= response.status_code >= 200 # 200 to 299 is OK
log_line = log_line_post.format(
Expand All @@ -74,8 +72,7 @@ def _escape_dict(data: dict) -> str:
self._logger.debug(msg=log_line)
return data_out.get("results")
self._logger.error(msg=log_line)
raise TPGalWSException(
f"HTTP --> {response.status_code}: {response.reason} || App --> {data_out.get('code')}: {data_out.get('message')}")
raise TPGalWSAppException(response)

def get(self, endpoint: str, ep_params: dict = None) -> dict:
"""
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from setuptools import setup, find_packages

VERSION = '0.1.0.3'
VERSION = '0.1.1.0'
DESCRIPTION = 'Python API wrapper for the galician public transport'
with open("README.md", "r", encoding="utf-8") as fh:
LONG_DESCRIPTION = fh.read()
Expand Down

0 comments on commit 618fce4

Please sign in to comment.