Exceptional commit

This commit is contained in:
krateng 2024-01-20 18:19:34 +01:00
parent fbe10930a2
commit 386f3c4a41
6 changed files with 58 additions and 36 deletions

View File

@ -25,6 +25,13 @@ __logmodulename__ = "apis"
cla = CleanerAgent()
# wrapper method: calls handle. final net to catch exceptions and map them to the handlers proper json / xml response
# handle method: finds the method for this path / query. can only raise InvalidMethodException
# scrobble: NOT the exposed scrobble method - helper for all APIs to scrobble their results with self-identification
class APIHandler:
# make these classes singletons
_instance = None
@ -64,17 +71,17 @@ class APIHandler:
response.status,result = self.handle(path,keys)
except Exception:
exceptiontype = sys.exc_info()[0]
if exceptiontype in self.errors:
response.status,result = self.errors[exceptiontype]
for exc_type, exc_response in self.errors.items():
if isinstance(exceptiontype, exc_type):
response.status, result = exc_response
log(f"Error with {self.__apiname__} API: {exceptiontype} (Request: {path})")
break
else:
# THIS SHOULD NOT HAPPEN
response.status, result = 500, {"status": "Unknown error", "code": 500}
log(f"Unhandled Exception with {self.__apiname__} API: {exceptiontype} (Request: {path})")
return result
#else:
# result = {"error":"Invalid scrobble protocol"}
# response.status = 500
def handle(self,path,keys):
@ -82,9 +89,9 @@ class APIHandler:
try:
methodname = self.get_method(path, keys)
method = self.methods[methodname]
except Exception:
log("Could not find a handler for method " + str(methodname) + " in API " + self.__apiname__,module="debug")
log("Keys: " + str(keys),module="debug")
except KeyError:
log(f"Could not find a handler for method {methodname} in API {self.__apiname__}", module="debug")
log(f"Keys: {keys}", module="debug")
raise InvalidMethodException()
return method(path, keys)
@ -92,7 +99,4 @@ class APIHandler:
def scrobble(self,rawscrobble,client=None):
# fixing etc is handled by the main scrobble function
try:
return database.incoming_scrobble(rawscrobble,api=self.__apiname__,client=client)
except Exception:
raise ScrobblingException()

View File

@ -3,4 +3,4 @@ class InvalidAuthException(Exception): pass
class InvalidMethodException(Exception): pass
class InvalidSessionKey(Exception): pass
class MalformedJSONException(Exception): pass
class ScrobblingException(Exception): pass

View File

@ -25,7 +25,7 @@ class Audioscrobbler(APIHandler):
InvalidAuthException: (401, {"error": 4, "message": "Invalid credentials"}),
InvalidMethodException: (200, {"error": 3, "message": "Invalid method"}),
InvalidSessionKey: (403, {"error": 9, "message": "Invalid session key"}),
ScrobblingException:(500,{"error":8,"message":"Operation failed"})
Exception: (500, {"error": 8, "message": "Operation failed"})
}
def get_method(self,pathnodes,keys):

View File

@ -27,7 +27,7 @@ class AudioscrobblerLegacy(APIHandler):
InvalidAuthException: (403, "BADAUTH\n"),
InvalidMethodException: (400, "FAILED\n"),
InvalidSessionKey: (403, "BADSESSION\n"),
ScrobblingException:(500,"FAILED\n")
Exception: (500, "FAILED\n")
}
def get_method(self,pathnodes,keys):

View File

@ -25,7 +25,7 @@ class Listenbrainz(APIHandler):
InvalidAuthException: (401, {"code": 401, "error": "Incorrect Authorization"}),
InvalidMethodException: (200, {"code": 200, "error": "Invalid Method"}),
MalformedJSONException: (400, {"code": 400, "error": "Invalid JSON document submitted."}),
ScrobblingException:(500,{"code":500,"error":"Unspecified server error."})
Exception: (500, {"code": 500, "error": "Unspecified server error."})
}
def get_method(self,pathnodes,keys):

View File

@ -1,5 +1,6 @@
from bottle import HTTPError
class EntityExists(Exception):
def __init__(self, entitydict):
self.entitydict = entitydict
@ -8,19 +9,28 @@ class EntityExists(Exception):
class TrackExists(EntityExists):
pass
class ArtistExists(EntityExists):
pass
class AlbumExists(EntityExists):
pass
# if the scrobbles dont match
class DuplicateTimestamp(Exception):
def __init__(self, existing_scrobble, rejected_scrobble):
self.existing_scrobble = existing_scrobble
self.rejected_scrobble = rejected_scrobble
# if it's the same scrobble
class DuplicateScrobble(EntityExists):
def __init__(self, scrobble):
self.scrobble = scrobble
class DatabaseNotBuilt(HTTPError):
def __init__(self):
super().__init__(
@ -34,11 +44,14 @@ class MissingScrobbleParameters(Exception):
def __init__(self, params=[]):
self.params = params
class MissingEntityParameter(Exception):
pass
class EntityDoesNotExist(HTTPError):
entitytype = 'Entity'
def __init__(self,entitydict):
self.entitydict = entitydict
super().__init__(
@ -46,9 +59,14 @@ class EntityDoesNotExist(HTTPError):
body=f"The {self.entitytype} '{self.entitydict}' does not exist in the database."
)
class ArtistDoesNotExist(EntityDoesNotExist):
entitytype = 'Artist'
class AlbumDoesNotExist(EntityDoesNotExist):
entitytype = 'Album'
class TrackDoesNotExist(EntityDoesNotExist):
entitytype = 'Track'