11import json
2- from requests import Session
2+ from typing import Any
3+ from requests import Session , RequestException
4+
5+
6+ class HTTPError (Exception ):
7+ """Http error wrapper with status code and (optional) response body"""
8+
9+ def __init__ (self , status : int , message : str , body : Any = None ):
10+ super ().__init__ (f"HTTP { status } : { message } " )
11+ self .status = status
12+ self .body = body
313
414
515class Request :
@@ -20,18 +30,28 @@ def __call__(self, headers=None, data=None, params=None, **kwargs):
2030 ):
2131 data = json .dumps (data )
2232
23- response = self .session .request (
24- method = self .http_method ,
25- url = self .url ,
26- headers = headers ,
27- params = params ,
28- data = data ,
29- ** kwargs ,
30- )
31-
32- # TODO: Better error responses
33- response .raise_for_status ()
34-
35- if response .content :
33+ try :
34+ response = self .session .request (
35+ method = self .http_method ,
36+ url = self .url ,
37+ headers = headers ,
38+ params = params ,
39+ data = data ,
40+ ** kwargs ,
41+ )
42+
43+ response .raise_for_status ()
44+ except RequestException as exc :
45+ status = getattr (exc .response , "status_code" , None )
46+ body = None
47+ try :
48+ body = exc .response .json ()
49+ except Exception :
50+ body = exc .response .txt if exc .response else None
51+ raise HTTPError (status = status or - 1 , message = str (exc ), body = body )
52+
53+ content_type = response .headers .get ("Content-Type" , "" )
54+ if "application/json" in content_type :
3655 return response .json ()
37- return None
56+
57+ return response .content
0 commit comments