Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise HTTP/JSON/API errors as exceptions #19

Merged
merged 4 commits into from
May 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions smartthings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ def log(**ad):
pprint.pprint(ad)

class SmartThings(object):

@staticmethod
def raise_request_errors(response):
if not response.ok:
raise Exception("HTTP error " + str(response.status_code) + ": " + response.url)

@staticmethod
def raise_api_errors(json_response):
if "error" in json_response:
if type(json_response["error"]) == bool:
error_type = json_response.get("type", "Unknown Error")
else:
error_type = json_response["error"]
error_message = json_response.get("message", "") + \
json_response.get("error_description", "")
raise Exception(error_type + ": " + error_message)

def __init__(self, verbose=True):
self.verbose = verbose
self.std = {}
Expand Down Expand Up @@ -66,8 +83,15 @@ def request_endpoints(self):
}

endpoints_response = requests.get(url=endpoints_url, params=endpoints_paramd)
self.endpointd = endpoints_response.json()[0]

try:
endpoints = endpoints_response.json()
except ValueError:
SmartThings.raise_request_errors(endpoints_response)
raise Exception("Received invalid JSON response")

SmartThings.raise_api_errors(endpoints)
self.endpointd = endpoints[0]
if self.verbose: iotdb_log.log(
"endpoints",
endpoints_url=endpoints_url,
Expand All @@ -86,7 +110,14 @@ def request_devices(self, device_type):
}

devices_response = requests.get(url=devices_url, params=devices_paramd, headers=devices_headerd)
self.deviceds = devices_response.json()

try:
self.deviceds = devices_response.json()
except ValueError:
SmartThings.raise_request_errors(devices_response)
raise Exception("Received invalid JSON response")
SmartThings.raise_api_errors(self.deviceds)

for switchd in self.deviceds:
switchd['url'] = "%s/%s" % ( devices_url, switchd['id'], )

Expand Down Expand Up @@ -115,6 +146,13 @@ def device_request(self, deviced, requestd):
data=json.dumps(requestd)
)

command_api_response = {}
try:
command_api_response = command_response.json()
except ValueError:
SmartThings.raise_request_errors(command_response)
SmartThings.raise_api_errors(command_api_response)

def device_types(self):
return dtypes

Expand Down