Handle unexpected errors in HTTP requests (bfxapi.rest._interface).

This commit is contained in:
Davide Casale
2024-04-04 16:42:08 +02:00
parent bdd78a817d
commit 65318beee9
2 changed files with 17 additions and 15 deletions

View File

@@ -3,14 +3,14 @@ import hmac
import json
from datetime import datetime
from enum import IntEnum
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, Any, List, NoReturn, Optional
import requests
from bfxapi._utils.json_decoder import JSONDecoder
from bfxapi._utils.json_encoder import JSONEncoder
from bfxapi.exceptions import InvalidCredentialError
from bfxapi.rest.exceptions import RequestParametersError, UnknownGenericError
from bfxapi.rest.exceptions import GenericError, RequestParameterError
if TYPE_CHECKING:
from requests.sessions import _Params
@@ -86,28 +86,30 @@ class Middleware:
return data
def __handle_error(self, error: List[Any]) -> None:
def __handle_error(self, error: List[Any]) -> NoReturn:
if error[1] == _Error.ERR_PARAMS:
raise RequestParametersError(
raise RequestParameterError(
"The request was rejected with the following parameter "
f"error: <{error[2]}>"
f"error: <{error[2]}>."
)
if error[1] == _Error.ERR_AUTH_FAIL:
raise InvalidCredentialError(
"Cannot authenticate with given API-KEY and API-SECRET."
"Can't authenticate with given API-KEY and API-SECRET."
)
if not error[1] or error[1] == _Error.ERR_UNK or error[1] == _Error.ERR_GENERIC:
raise UnknownGenericError(
"The server replied to the request with a generic error with "
f"the following message: <{error[2]}>."
raise GenericError(
"The request was rejected with the following generic "
f"error: <{error[2]}>."
)
raise RuntimeError(
f"The request was rejected with an unexpected error: <{error}>."
)
def __get_authentication_headers(self, endpoint: str, data: Optional[str] = None):
assert (
self.__api_key and self.__api_secret
), "API-KEY and API-SECRET must be strings."
assert self.__api_key and self.__api_secret
nonce = str(round(datetime.now().timestamp() * 1_000_000))

View File

@@ -1,9 +1,9 @@
from bfxapi.exceptions import BfxBaseException
class RequestParametersError(BfxBaseException):
class RequestParameterError(BfxBaseException):
pass
class UnknownGenericError(BfxBaseException):
class GenericError(BfxBaseException):
pass