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() 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: class APIHandler:
# make these classes singletons # make these classes singletons
_instance = None _instance = None
@ -64,35 +71,32 @@ class APIHandler:
response.status,result = self.handle(path,keys) response.status,result = self.handle(path,keys)
except Exception: except Exception:
exceptiontype = sys.exc_info()[0] exceptiontype = sys.exc_info()[0]
if exceptiontype in self.errors: for exc_type, exc_response in self.errors.items():
response.status,result = self.errors[exceptiontype] if isinstance(exceptiontype, exc_type):
response.status, result = exc_response
log(f"Error with {self.__apiname__} API: {exceptiontype} (Request: {path})") log(f"Error with {self.__apiname__} API: {exceptiontype} (Request: {path})")
break
else: else:
response.status,result = 500,{"status":"Unknown error","code":500} # THIS SHOULD NOT HAPPEN
response.status, result = 500, {"status": "Unknown error", "code": 500}
log(f"Unhandled Exception with {self.__apiname__} API: {exceptiontype} (Request: {path})") log(f"Unhandled Exception with {self.__apiname__} API: {exceptiontype} (Request: {path})")
return result return result
#else:
# result = {"error":"Invalid scrobble protocol"}
# response.status = 500
def handle(self,path,keys): def handle(self,path,keys):
try: try:
methodname = self.get_method(path,keys) methodname = self.get_method(path, keys)
method = self.methods[methodname] method = self.methods[methodname]
except Exception: except KeyError:
log("Could not find a handler for method " + str(methodname) + " in API " + self.__apiname__,module="debug") log(f"Could not find a handler for method {methodname} in API {self.__apiname__}", module="debug")
log("Keys: " + str(keys),module="debug") log(f"Keys: {keys}", module="debug")
raise InvalidMethodException() raise InvalidMethodException()
return method(path,keys) return method(path, keys)
def scrobble(self,rawscrobble,client=None): def scrobble(self,rawscrobble,client=None):
# fixing etc is handled by the main scrobble function # fixing etc is handled by the main scrobble function
try:
return database.incoming_scrobble(rawscrobble,api=self.__apiname__,client=client) 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 InvalidMethodException(Exception): pass
class InvalidSessionKey(Exception): pass class InvalidSessionKey(Exception): pass
class MalformedJSONException(Exception): pass class MalformedJSONException(Exception): pass
class ScrobblingException(Exception): pass

View File

@ -21,11 +21,11 @@ class Audioscrobbler(APIHandler):
"track.scrobble":self.submit_scrobble "track.scrobble":self.submit_scrobble
} }
self.errors = { self.errors = {
BadAuthException:(400,{"error":6,"message":"Requires authentication"}), BadAuthException: (400, {"error": 6, "message": "Requires authentication"}),
InvalidAuthException:(401,{"error":4,"message":"Invalid credentials"}), InvalidAuthException: (401, {"error": 4, "message": "Invalid credentials"}),
InvalidMethodException:(200,{"error":3,"message":"Invalid method"}), InvalidMethodException: (200, {"error": 3, "message": "Invalid method"}),
InvalidSessionKey:(403,{"error":9,"message":"Invalid session key"}), 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): def get_method(self,pathnodes,keys):

View File

@ -23,11 +23,11 @@ class AudioscrobblerLegacy(APIHandler):
"scrobble":self.submit_scrobble "scrobble":self.submit_scrobble
} }
self.errors = { self.errors = {
BadAuthException:(403,"BADAUTH\n"), BadAuthException: (403, "BADAUTH\n"),
InvalidAuthException:(403,"BADAUTH\n"), InvalidAuthException: (403, "BADAUTH\n"),
InvalidMethodException:(400,"FAILED\n"), InvalidMethodException: (400, "FAILED\n"),
InvalidSessionKey:(403,"BADSESSION\n"), InvalidSessionKey: (403, "BADSESSION\n"),
ScrobblingException:(500,"FAILED\n") Exception: (500, "FAILED\n")
} }
def get_method(self,pathnodes,keys): def get_method(self,pathnodes,keys):

View File

@ -21,11 +21,11 @@ class Listenbrainz(APIHandler):
"validate-token":self.validate_token "validate-token":self.validate_token
} }
self.errors = { self.errors = {
BadAuthException:(401,{"code":401,"error":"You need to provide an Authorization header."}), BadAuthException: (401, {"code": 401, "error": "You need to provide an Authorization header."}),
InvalidAuthException:(401,{"code":401,"error":"Incorrect Authorization"}), InvalidAuthException: (401, {"code": 401, "error": "Incorrect Authorization"}),
InvalidMethodException:(200,{"code":200,"error":"Invalid Method"}), InvalidMethodException: (200, {"code": 200, "error": "Invalid Method"}),
MalformedJSONException:(400,{"code":400,"error":"Invalid JSON document submitted."}), 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): def get_method(self,pathnodes,keys):

View File

@ -1,44 +1,57 @@
from bottle import HTTPError from bottle import HTTPError
class EntityExists(Exception): class EntityExists(Exception):
def __init__(self,entitydict): def __init__(self, entitydict):
self.entitydict = entitydict self.entitydict = entitydict
class TrackExists(EntityExists): class TrackExists(EntityExists):
pass pass
class ArtistExists(EntityExists): class ArtistExists(EntityExists):
pass pass
class AlbumExists(EntityExists): class AlbumExists(EntityExists):
pass pass
# if the scrobbles dont match
class DuplicateTimestamp(Exception): class DuplicateTimestamp(Exception):
def __init__(self,existing_scrobble,rejected_scrobble): def __init__(self, existing_scrobble, rejected_scrobble):
self.existing_scrobble = existing_scrobble self.existing_scrobble = existing_scrobble
self.rejected_scrobble = rejected_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): class DatabaseNotBuilt(HTTPError):
def __init__(self): def __init__(self):
super().__init__( super().__init__(
status=503, status=503,
body="The Maloja Database is being upgraded to support new Maloja features. This could take a while.", body="The Maloja Database is being upgraded to support new Maloja features. This could take a while.",
headers={"Retry-After":120} headers={"Retry-After": 120}
) )
class MissingScrobbleParameters(Exception): class MissingScrobbleParameters(Exception):
def __init__(self,params=[]): def __init__(self, params=[]):
self.params = params self.params = params
class MissingEntityParameter(Exception): class MissingEntityParameter(Exception):
pass pass
class EntityDoesNotExist(HTTPError): class EntityDoesNotExist(HTTPError):
entitytype = 'Entity' entitytype = 'Entity'
def __init__(self,entitydict): def __init__(self,entitydict):
self.entitydict = entitydict self.entitydict = entitydict
super().__init__( super().__init__(
@ -46,9 +59,14 @@ class EntityDoesNotExist(HTTPError):
body=f"The {self.entitytype} '{self.entitydict}' does not exist in the database." body=f"The {self.entitytype} '{self.entitydict}' does not exist in the database."
) )
class ArtistDoesNotExist(EntityDoesNotExist): class ArtistDoesNotExist(EntityDoesNotExist):
entitytype = 'Artist' entitytype = 'Artist'
class AlbumDoesNotExist(EntityDoesNotExist): class AlbumDoesNotExist(EntityDoesNotExist):
entitytype = 'Album' entitytype = 'Album'
class TrackDoesNotExist(EntityDoesNotExist): class TrackDoesNotExist(EntityDoesNotExist):
entitytype = 'Track' entitytype = 'Track'