|
| 1 | +from collections.abc import Callable |
| 2 | +from functools import partial, update_wrapper |
| 3 | +from http import HTTPStatus |
| 4 | +from typing import Any, ParamSpec, TypeVar |
| 5 | + |
| 6 | +from mpt_api_client.exceptions import MPTHttpError as APIException |
| 7 | +from requests import RequestException, Response |
| 8 | + |
| 9 | +ErrorFactory = Callable[[str, str], Exception] |
| 10 | +CallableParams = ParamSpec("CallableParams") |
| 11 | +RetType = TypeVar("RetType") |
| 12 | + |
| 13 | + |
| 14 | +def _parse_bad_request_message(response: Response) -> str: |
| 15 | + try: |
| 16 | + response_body = response.json() |
| 17 | + except ValueError: |
| 18 | + return response.text |
| 19 | + |
| 20 | + response_errors = response_body.get("errors", {}) if isinstance(response_body, dict) else {} |
| 21 | + if not isinstance(response_errors, dict) or not response_errors: |
| 22 | + return response.text |
| 23 | + |
| 24 | + return "\n".join( |
| 25 | + ( |
| 26 | + f"{field}: {error_details[0]}" |
| 27 | + if isinstance(error_details, (list, tuple)) and error_details |
| 28 | + else f"{field}: {error_details}" |
| 29 | + ) |
| 30 | + for field, error_details in response_errors.items() |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +class HttpErrorWrapper[**CallableParams, RetType]: |
| 35 | + """Wrap callables and normalize RequestException to domain error.""" |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + func: Callable[CallableParams, RetType], |
| 40 | + error_factory: ErrorFactory, |
| 41 | + ): |
| 42 | + self._func = func |
| 43 | + self._error_factory = error_factory |
| 44 | + update_wrapper(self, func) |
| 45 | + |
| 46 | + def __call__( |
| 47 | + self, |
| 48 | + *args: CallableParams.args, |
| 49 | + **kwargs: CallableParams.kwargs, |
| 50 | + ) -> RetType: |
| 51 | + """Execute wrapped callable and map RequestException to domain error.""" |
| 52 | + try: |
| 53 | + return self._func(*args, **kwargs) |
| 54 | + except RequestException as error: |
| 55 | + if error.response is None: |
| 56 | + msg = "No response" |
| 57 | + raise self._error_factory(str(error), msg) from error |
| 58 | + |
| 59 | + if error.response.status_code != HTTPStatus.BAD_REQUEST: |
| 60 | + msg = error.response.text |
| 61 | + raise self._error_factory(str(error), msg) from error |
| 62 | + |
| 63 | + msg = _parse_bad_request_message(error.response) |
| 64 | + raise self._error_factory(str(error), msg) from error |
| 65 | + |
| 66 | + def __get__(self, instance: Any, owner: type[Any] | None = None) -> Any: |
| 67 | + if instance is None: |
| 68 | + return self |
| 69 | + |
| 70 | + return partial(self.__call__, instance) |
| 71 | + |
| 72 | + |
| 73 | +class ApiErrorWrapper[**CallableParams, RetType]: |
| 74 | + """Wrap callables and normalize APIException to domain error.""" |
| 75 | + |
| 76 | + def __init__( |
| 77 | + self, |
| 78 | + func: Callable[CallableParams, RetType], |
| 79 | + error_factory: ErrorFactory, |
| 80 | + ): |
| 81 | + self._func = func |
| 82 | + self._error_factory = error_factory |
| 83 | + update_wrapper(self, func) |
| 84 | + |
| 85 | + def __call__( |
| 86 | + self, |
| 87 | + *args: CallableParams.args, |
| 88 | + **kwargs: CallableParams.kwargs, |
| 89 | + ) -> RetType: |
| 90 | + """Execute wrapped callable and map APIException to domain error.""" |
| 91 | + try: |
| 92 | + return self._func(*args, **kwargs) |
| 93 | + except APIException as error: |
| 94 | + raise self._error_factory(str(error), error.body) from error |
| 95 | + |
| 96 | + def __get__(self, instance: Any, owner: type[Any] | None = None) -> Any: |
| 97 | + if instance is None: |
| 98 | + return self |
| 99 | + |
| 100 | + return partial(self.__call__, instance) |
0 commit comments