@@ -37,6 +37,23 @@ def log(**ad):
37
37
pprint .pprint (ad )
38
38
39
39
class SmartThings (object ):
40
+
41
+ @staticmethod
42
+ def raise_request_errors (response ):
43
+ if not response .ok :
44
+ raise Exception ("HTTP error " + str (response .status_code ) + ": " + response .url )
45
+
46
+ @staticmethod
47
+ def raise_api_errors (json_response ):
48
+ if "error" in json_response :
49
+ if type (json_response ["error" ]) == bool :
50
+ error_type = json_response .get ("type" , "Unknown Error" )
51
+ else :
52
+ error_type = json_response ["error" ]
53
+ error_message = json_response .get ("message" , "" ) + \
54
+ json_response .get ("error_description" , "" )
55
+ raise Exception (error_type + ": " + error_message )
56
+
40
57
def __init__ (self , verbose = True ):
41
58
self .verbose = verbose
42
59
self .std = {}
@@ -66,8 +83,15 @@ def request_endpoints(self):
66
83
}
67
84
68
85
endpoints_response = requests .get (url = endpoints_url , params = endpoints_paramd )
69
- self .endpointd = endpoints_response .json ()[0 ]
86
+
87
+ try :
88
+ endpoints = endpoints_response .json ()
89
+ except ValueError :
90
+ SmartThings .raise_request_errors (endpoints_response )
91
+ raise Exception ("Received invalid JSON response" )
70
92
93
+ SmartThings .raise_api_errors (endpoints )
94
+ self .endpointd = endpoints [0 ]
71
95
if self .verbose : iotdb_log .log (
72
96
"endpoints" ,
73
97
endpoints_url = endpoints_url ,
@@ -86,7 +110,14 @@ def request_devices(self, device_type):
86
110
}
87
111
88
112
devices_response = requests .get (url = devices_url , params = devices_paramd , headers = devices_headerd )
89
- self .deviceds = devices_response .json ()
113
+
114
+ try :
115
+ self .deviceds = devices_response .json ()
116
+ except ValueError :
117
+ SmartThings .raise_request_errors (devices_response )
118
+ raise Exception ("Received invalid JSON response" )
119
+ SmartThings .raise_api_errors (self .deviceds )
120
+
90
121
for switchd in self .deviceds :
91
122
switchd ['url' ] = "%s/%s" % ( devices_url , switchd ['id' ], )
92
123
@@ -115,6 +146,13 @@ def device_request(self, deviced, requestd):
115
146
data = json .dumps (requestd )
116
147
)
117
148
149
+ command_api_response = {}
150
+ try :
151
+ command_api_response = command_response .json ()
152
+ except ValueError :
153
+ SmartThings .raise_request_errors (command_response )
154
+ SmartThings .raise_api_errors (command_api_response )
155
+
118
156
def device_types (self ):
119
157
return dtypes
120
158
0 commit comments