rsc-dev / pyamaha

Python implementation of Yamaha Extended Control API Specification.
MIT License
84 stars 22 forks source link

General exception handling #7

Closed runningman84 closed 7 years ago

runningman84 commented 7 years ago

Right now I have to check each response for the response status. It would be cool if your class would optionally throw Exceptions bases on RESPONSE_CODE. This would result in a much clearer code at my side. Otherwise I have to implement some kind of wrapper or proxy for your class.

runningman84 commented 7 years ago

This is my current code: https://gist.github.com/runningman84/5464ec4dc39b10efd10828ca7cef25d0

runningman84 commented 7 years ago

Ok it solved it in my class with some proxy function

    def _proxy_request(self, *args):

        if isinstance(args[0], str):
            # get request
            _LOGGER.debug("Sending get request:\n{}".format(args[0]))
            res = self._device.request(args[0])
        else:
            # post request
            _LOGGER.debug("Sending post request:\n{}".format(args[0]))
            res = self._device.request(*(args[0]))

        try:
            res_json = res.json()
            _LOGGER.debug("Got response:\n{}".format(res_json))
            response_code = res_json['response_code']
        except Exception:
            raise('Could not parse response')

        if response_code > 0:
            raise Exception(RESPONSE_CODE[response_code])

        return res_json