watchforstock / evohome-client

Python client to access the Evohome web service
Apache License 2.0
88 stars 52 forks source link

Better handling of exceptions #66

Closed zxdavb closed 5 years ago

zxdavb commented 5 years ago

On invocation, the first RESTful API call is in _populate_user_info(). Notably, it can return an error, for example (see #53):

[{ "code": "LatestEulaNotAccepted", "message": "Latest Eula is not accepted." }]

In addition, any of the API calls could return (via a HTML_STATUS_429):

[{  "code": "TooManyRequests", "message": "Request count limitation exceeded..." }]

This PR adds response.raise_for_status() after every requests call, but the handling is different for the first as we wont get the (potentially useful) error message otherwise.

It removes the two try / except blocks, which were unsatisfactory (but did provide a useful message in a round-about way):

except Exception as error:      
    raise Exception('Invalid user_data: %s' % repr(self.user_data)) from error

In this case, a (say) 429 had not been caught much earlier in the code and (for example) self.user_data contains the corresponding error message (TooManyRequests) rather than the expected JSON.

Subsequently, this line:

user_id = self.user_data['userInfo']['userID']

causes an TypeError since:

self.user_data == [{ "code": "LatestEulaNotAccepted", "message": "Latest Eula is not accepted." }]

This code addresses the issues raised in #53, but replaces the corresponding fix, #54, with potentially better code.

zxdavb commented 5 years ago

For example:

>>> from evohomeclient import EvohomeClient
>>> c = EvohomeClient("bad_username", "bad_password")
>>> print(list(c.temperatures(force_refresh=True)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/srv/hass/lib/python3.6/site-packages/evohomeclient/__init__.py", line 124, in temperatures
    self._populate_full_data(force_refresh)
  File "/srv/hass/lib/python3.6/site-packages/evohomeclient/__init__.py", line 62, in _populate_full_data
    self._populate_user_info()
  File "/srv/hass/lib/python3.6/site-packages/evohomeclient/__init__.py", line 117, in _populate_user_info
    raise requests.HTTPError(message)
requests.exceptions.HTTPError: HTTP Status = 401, Response = [
  {
    "code": "EmailOrPasswordIncorrect",
    "message": "The email or password provided is incorrect."
  }
]