Skip to content

Commit 7c297bf

Browse files
adamantikecjbell
andauthored
fix: Correctly catch JSONDecodeError exceptions (#26)
Problem: Since `requests` version `2.27.0` [1], the library has introduced its own `JSONDecodeError` exception, to fix inconsistencies between `json` and `simplejson`. From that version onwards, if the project has `simplejson` installed, the exception raised by `json()` is a subclass of `simplejson.JSONDecodeError` instead of `json.JSONDecodeError`. The Knock client is only handling `json.JSONDecodeError`, so in projects where `simplejson` is installed, the exception is raised when `json()` is not able to decode the response body (e.g. in 204 responses). How to reproduce: In a new virtualenv, install `requests`. ```python >>> import json, requests >>> isinstance(requests.exceptions.JSONDecodeError("", "", 0), json.JSONDecodeError) True ``` Now, install `simplejson`. ```python >>> import json, requests, simplejson >>> isinstance(requests.exceptions.JSONDecodeError("", "", 0), json.JSONDecodeError) False >>> isinstance(requests.exceptions.JSONDecodeError("", "", 0), simplejson.JSONDecodeError) True ``` Solution: When available, import the `JSONDecodeError` class provided by `requests`, and use that one to handle exceptions from the `json()` method. Otherwise, first try to use the exception provided by `simplejson`, and only use the one from `json` if none is available. [1] psf/requests@db575ee Co-authored-by: Chris Bell <[email protected]>
1 parent d863b36 commit 7c297bf

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

knockapi/client.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
import requests
2-
from json.decoder import JSONDecodeError
32
from knockapi.__about__ import __version__
43

4+
try:
5+
from requests.exceptions import JSONDecodeError
6+
except ImportError:
7+
try:
8+
from simplejson import JSONDecodeError
9+
except ImportError:
10+
from json.decoder import JSONDecodeError
11+
12+
from ._version import __version__
513

614
class Connection(object):
715
def __init__(self, api_key, host='https://api.knock.app', timeout=None):

0 commit comments

Comments
 (0)