StannisGr/yaschedule

Implement http error handling

Opened this issue · 0 comments

I think it would be nice to implement base http error handling
https://stackoverflow.com/questions/16511337/correct-way-to-try-except-using-python-requests-module

Because sometimes we can get JSONDecodeError and reason is not clear at first sight

Example:

from yaschedule.core import YaSchedule
yaschedule = YaSchedule('bad_token')
yaschedule.get_all_stations()

will produce:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/requests/models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.10/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/a/projects/yaschedule/t.py", line 14, in <module>
    x1 = yaschedule.get_all_stations()
  File "/home/a/projects/yaschedule/yaschedule/core.py", line 63, in get_all_stations
    return self.__get_response(api_method_url, payload)
  File "/home/a/projects/yaschedule/yaschedule/core.py", line 52, in __get_response
    return response.json()
  File "/usr/local/lib/python3.10/dist-packages/requests/models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

As minimal handling I suggest to use

if response.status == 200:
	return response.json()

instead of

return response.json()