44from typing import ParamSpec , TypeVar
55
66from mpt_api_client .exceptions import MPTHttpError as APIException
7- from requests import RequestException
7+ from requests import RequestException , Response
88
99CallableParams = ParamSpec ("CallableParams" )
1010RetType = TypeVar ("RetType" )
@@ -25,7 +25,27 @@ def __str__(self) -> str:
2525 return f"{ self ._request_msg } with response body { self ._response_body } "
2626
2727
28- def wrap_http_error [** CallableParams , RetType ]( # noqa: C901
28+ def _parse_bad_request_message (response : Response ) -> str :
29+ try :
30+ response_body = response .json ()
31+ except ValueError :
32+ return str (response .content )
33+
34+ response_errors = response_body .get ("errors" , {}) if isinstance (response_body , dict ) else {}
35+ if not isinstance (response_errors , dict ) or not response_errors :
36+ return str (response .content )
37+
38+ return "\n " .join (
39+ (
40+ f"{ field } : { error_details [0 ]} "
41+ if isinstance (error_details , (list , tuple )) and error_details
42+ else f"{ field } : { error_details } "
43+ )
44+ for field , error_details in response_errors .items ()
45+ )
46+
47+
48+ def wrap_http_error [** CallableParams , RetType ](
2949 func : Callable [CallableParams , RetType ],
3050) -> Callable [CallableParams , RetType ]:
3151 """Decorator to wrap HTTP request functions and handle RequestException.
@@ -45,18 +65,13 @@ def _wrapper(*args: CallableParams.args, **kwargs: CallableParams.kwargs) -> Ret
4565 except RequestException as error :
4666 if error .response is None :
4767 msg = "No response"
48- elif error .response .status_code == HTTPStatus .BAD_REQUEST :
49- response_body = error .response .json ()
50-
51- msg = ""
52- if "errors" in response_body :
53- for field , error_details in response_body ["errors" ].items ():
54- msg += f"{ field } : { error_details [0 ]} \n "
55- else :
56- msg = str (error .response .content )
57- else :
68+ raise MPTAPIError (str (error ), msg ) from error
69+
70+ if error .response .status_code != HTTPStatus .BAD_REQUEST :
5871 msg = str (error .response .content )
72+ raise MPTAPIError (str (error ), msg ) from error
5973
74+ msg = _parse_bad_request_message (error .response )
6075 raise MPTAPIError (str (error ), msg ) from error
6176
6277 return _wrapper
0 commit comments