pythonhttpx

What exceptions can be raised by Python HTTPX's json() method?


The excellent Python HTTPX package has a .json() method for conveniently decoding resposnes that are in JSON format. But the documentation does not mention what exceptions can be raised by .json(), and even looking through the code, it is not obvious to me what the possible exceptions might be.

For purposes of writing code like the following,

try:
    return response.json()
except EXCEPTION:
    print('This is not the JSON you are looking for')

what exceptions should I test for?


Solution

  • even looking through the code, it is not obvious to me what the possible exceptions might be.

    Here's my attempt at looking through it:

    def json(self, **kwargs: typing.Any) -> typing.Any:
        if self.charset_encoding is None and self.content and len(self.content) > 3:
            encoding = guess_json_utf(self.content)
            if encoding is not None:
                return jsonlib.loads(self.content.decode(encoding), **kwargs)
        return jsonlib.loads(self.text, **kwargs)
    

    tl;dr: the possible exceptions that make sense to catch are JSONDecodeError (the response is not valid JSON - this includes e.g. an empty response) and UnicodeDecodeError (the response is corrupt in some way, for example it mixes bytes intended to encode text in two different ways, or it's supposed to be UTF-8 but contains bytes that are illegal in that encoding; or it's encoded using a non-UTF scheme, such as Latin-1, in a way that is incompatible with the corresponding guessed UTF scheme, and doesn't advertise the encoding in the header).