Skip to content

Commit

Permalink
feat: add fine grained errors raised from http operations (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
ooliver1 committed Feb 4, 2023
1 parent 3bc39f4 commit b1f4042
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
name: Running black in all files.

- repo: https://github.com/pycqa/isort
rev: 5.11.4
rev: 5.12.0
hooks:
- id: isort
name: Running isort in all files.
Expand Down
12 changes: 12 additions & 0 deletions docs/api/errors-and-warnings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ Errors
- :exc:`PlayerNotConnected`
- :exc:`NodeAlreadyConnected`
- :exc:`NoNodesAvailable`
- :exc:`HTTPException`
- :exc:`HTTPBadRequest`
- :exc:`HTTPUnauthorized`
- :exc:`HTTPNotFound`


.. autoexception:: MaficException
Expand All @@ -39,6 +43,14 @@ Errors

.. autoexception:: NodeAlreadyConnected

.. autoexception:: HTTPException

.. autoexception:: HTTPBadRequest

.. autoexception:: HTTPUnauthorized

.. autoexception:: HTTPNotFound

Warnings
--------

Expand Down
35 changes: 35 additions & 0 deletions mafic/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
from .typings import ExceptionSeverity, LavalinkException

__all__ = (
"HTTPBadRequest",
"HTTPException",
"HTTPNotFound",
"HTTPUnauthorized",
"LibraryCompatibilityError",
"MaficException",
"MultipleCompatibleLibraries",
Expand Down Expand Up @@ -115,3 +119,34 @@ class NoNodesAvailable(MaficException):

def __init__(self) -> None:
super().__init__("No nodes are available to handle this player.")


class HTTPException(MaficException):
"""An issue occured when trying to make a request to the Lavalink REST API."""

def __init__(self, status: int, message: str) -> None:
super().__init__(f"An HTTP error occured: {message} ({status})")

self.status: int = status
self.message: str = message


class HTTPBadRequest(HTTPException):
"""This is raised when a bad request is made to the Lavalink REST API."""

def __init__(self, message: str) -> None:
super().__init__(400, message)


class HTTPUnauthorized(HTTPException):
"""This is raised when an unauthorized request is made to the Lavalink REST API."""

def __init__(self, message: str) -> None:
super().__init__(401, message)


class HTTPNotFound(HTTPException):
"""This is raised when a request is made to a non-existent endpoint."""

def __init__(self, message: str) -> None:
super().__init__(404, message)
16 changes: 11 additions & 5 deletions mafic/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from mafic.typings.http import TrackWithInfo

from .__libraries import MISSING, ExponentialBackoff, dumps, loads
from .errors import NodeAlreadyConnected, TrackLoadException
from .errors import *
from .ip import (
BalancingIPRoutePlannerStatus,
NanoIPRoutePlannerStatus,
Expand Down Expand Up @@ -828,8 +828,16 @@ async def __request(
headers={"Authorization": self.__password},
) as resp:
if not (200 <= resp.status < 300):
# TODO: raise proper error
raise RuntimeError(f"Got status code {resp.status} from lavalink.")
text = await resp.text()

if resp.status == 400:
raise HTTPBadRequest(text)
if resp.status == 401:
raise HTTPUnauthorized(text)
elif resp.status == 404:
raise HTTPNotFound(text)
else:
raise HTTPException(status=resp.status, message=text)

_log.debug(
"Received status %s from lavalink from path %s", resp.status, path
Expand Down Expand Up @@ -864,7 +872,6 @@ async def fetch_tracks(
if not URL_REGEX.match(query):
query = f"{search_type}:{query}"

# TODO: handle errors from lavalink
data: TrackLoadingResult = await self.__request(
"GET", "/loadtracks", params={"identifier": query}
)
Expand Down Expand Up @@ -900,7 +907,6 @@ async def decode_track(self, track: str) -> Track:
:meth:`decode_tracks`
"""

# TODO: handle errors from lavalink
info: TrackInfo = await self.__request(
"GET", "/decodetrack", params={"encodedTrack": track}
)
Expand Down

0 comments on commit b1f4042

Please sign in to comment.