Skip to content

Commit dec37a8

Browse files
authored
Merge pull request #19 from kizzard/fix/raise_errors
Raise HTTP/JSON/API errors as exceptions
2 parents e546d4c + 6349651 commit dec37a8

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

smartthings.py

+40-2
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,23 @@ def log(**ad):
3737
pprint.pprint(ad)
3838

3939
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+
4057
def __init__(self, verbose=True):
4158
self.verbose = verbose
4259
self.std = {}
@@ -66,8 +83,15 @@ def request_endpoints(self):
6683
}
6784

6885
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")
7092

93+
SmartThings.raise_api_errors(endpoints)
94+
self.endpointd = endpoints[0]
7195
if self.verbose: iotdb_log.log(
7296
"endpoints",
7397
endpoints_url=endpoints_url,
@@ -86,7 +110,14 @@ def request_devices(self, device_type):
86110
}
87111

88112
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+
90121
for switchd in self.deviceds:
91122
switchd['url'] = "%s/%s" % ( devices_url, switchd['id'], )
92123

@@ -115,6 +146,13 @@ def device_request(self, deviced, requestd):
115146
data=json.dumps(requestd)
116147
)
117148

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+
118156
def device_types(self):
119157
return dtypes
120158

0 commit comments

Comments
 (0)