Fix inconsistent exception type in response.json() method (#5856)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Steve Berdy · committed by GitHub · parent 941a77f · Browse files · 7 files·+47 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+47 added−18 removed
- tests:+6 added−1 removed
- other:+41 added−17 removed
Provenance
- Commit
db575ee- Tree
27b09b0- Author
Steve Berdy <86739818+steveberdy@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
941a77f
7 files changed+47 added−18 removed
modified:docs/user/quickstart.rst+3 added-3 removed
151 unmodified lines152 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...153 154 In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if155 the response gets a 204 (No Content), or if the response contains invalid JSON,156-attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is157-installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or158-``json.JSONDecodeError`` on Python 3.156+attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception157+provides interoperability for multiple exceptions that may be thrown by different158+python versions and json serialization libraries.159 160 It should be noted that the success of the call to ``r.json()`` does **not**161 indicate the success of the response. Some servers may return a JSON object in a162 failed response (e.g. error details with HTTP 500). Such JSON will be decoded407 unmodified linesmodified:requests/__init__.py+1 added-1 removed
137 unmodified lines138 from .status_codes import codes139 from .exceptions import (140 RequestException, Timeout, URLRequired,141 TooManyRedirects, HTTPError, ConnectionError,142- FileModeWarning, ConnectTimeout, ReadTimeout142+ FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError143 )144 145 # Set default logging handler to avoid "No handler found" warnings.146 import logging6 unmodified linesmodified:requests/compat.py+7 added-1 removed
26 unmodified lines27 28 #: Python 3.x?29 is_py3 = (_ver[0] == 3)30 31+has_simplejson = False32 try:33 import simplejson as json34+ has_simplejson = True35 except ImportError:36 import json37 38 # ---------11 unmodified lines50 from StringIO import StringIO51 # Keep OrderedDict for backwards compatibility.52 from collections import Callable, Mapping, MutableMapping, OrderedDict53 52-54 builtin_str = str55 bytes = str56 str = unicode57 basestring = basestring58 numeric_types = (int, long, float)59 integer_types = (int, long)60+ JSONDecodeError = ValueError61 62 elif is_py3:63 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag64 from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment2 unmodified lines67 from io import StringIO68 # Keep OrderedDict for backwards compatibility.69 from collections import OrderedDict70 from collections.abc import Callable, Mapping, MutableMapping71+ if has_simplejson:72+ from simplejson import JSONDecodeError73+ else:74+ from json import JSONDecodeError75 76 builtin_str = str77 str = str78 bytes = bytes3 unmodified linesmodified:requests/exceptions.py+6 added
6 unmodified lines7 This module contains the set of Requests' exceptions.8 """9 from urllib3.exceptions import HTTPError as BaseHTTPError10 11+from .compat import JSONDecodeError as CompatJSONDecodeError12 13+14 class RequestException(IOError):15 """There was an ambiguous exception that occurred while handling your16 request.17 """12 unmodified lines30 class InvalidJSONError(RequestException):31 """A JSON error occurred."""32 33 34+class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):35+ """Couldn't decode the text into json"""36+37+38 class HTTPError(RequestException):39 """An HTTP error occurred."""40 41 92 unmodified linesmodified:requests/models.py+18 added-11 removed
27 unmodified lines28 from .auth import HTTPBasicAuth29 from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar30 from .exceptions import (31 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,32- ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError)32+ ContentDecodingError, ConnectionError, StreamConsumedError,33+ InvalidJSONError)34+from .exceptions import JSONDecodeError as RequestsJSONDecodeError35 from ._internal_utils import to_native_string, unicode_is_ascii36 from .utils import (37 guess_filename, get_auth_from_url, requote_uri,38 stream_decode_response_unicode, to_key_val_list, parse_header_links,39 iter_slices, guess_json_utf, super_len, check_header_validity)40 from .compat import (41 Callable, Mapping,42 cookielib, urlunparse, urlsplit, urlencode, str, bytes,41- is_py2, chardet, builtin_str, basestring)43+ is_py2, chardet, builtin_str, basestring, JSONDecodeError)44 from .compat import json as complexjson45 from .status_codes import codes46 47 #: The set of HTTP status codes that indicate an automatically421 unmodified lines469 # provides this natively, but Python 3 gives a Unicode string.470 content_type = 'application/json'471 472 try:471- body = complexjson.dumps(json, allow_nan=False)473+ body = complexjson.dumps(json, allow_nan=False)474 except ValueError as ve:473- raise InvalidJSONError(ve, request=self)475+ raise InvalidJSONError(ve, request=self)476 477 if not isinstance(body, bytes):478 body = body.encode('utf-8')479 403 unmodified lines883 def json(self, **kwargs):884 r"""Returns the json-encoded content of a response, if any.885 886 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.885- :raises simplejson.JSONDecodeError: If the response body does not886- contain valid json and simplejson is installed.887- :raises json.JSONDecodeError: If the response body does not contain888- valid json and simplejson is not installed on Python 3.889- :raises ValueError: If the response body does not contain valid890- json and simplejson is not installed on Python 2. 887+ :raises requests.exceptions.JSONDecodeError: If the response body does not888+ contain valid json.889 """890 891 if not self.encoding and self.content and len(self.content) > 3:892 # No encoding set. JSON RFC 4627 section 3 states we should expect11 unmodified lines904 # but some other 8-bit codec. This is an RFC violation,905 # and the server didn't bother to tell us what codec *was*906 # used.907 pass910- return complexjson.loads(self.text, **kwargs)908 909+ try:910+ return complexjson.loads(self.text, **kwargs)911+ except JSONDecodeError as e:912+ # Catch JSON-related errors and raise as requests.JSONDecodeError913+ # This aliases json.JSONDecodeError and simplejson.JSONDecodeError914+ if is_py2: # e is a ValueError915+ raise RequestsJSONDecodeError(e.message)916+ else:917+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)918+919 @property920 def links(self):921 """Returns the parsed header links of the response, if any."""922 51 unmodified linesmodified:tests/test_requests.py+6 added-1 removed
2568 unmodified lines2569 2570 def test_post_json_nan(self, httpbin):2571 data = {"foo": float("nan")}2572 with pytest.raises(requests.exceptions.InvalidJSONError):2573- r = requests.post(httpbin('post'), json=data)2573+ r = requests.post(httpbin('post'), json=data)2574+2575+ def test_json_decode_compatibility(self, httpbin):2576+ r = requests.get(httpbin('bytes/20'))2577+ with pytest.raises(requests.exceptions.JSONDecodeError):2578+ r.json()modified:HISTORY.md+6 added-1 removed
2 unmodified lines3 4 dev5 ---6 7-- \[Short description of non-trivial change.\]7+- \[Short description of non-trivial change.\]8 9+- Added a `requests.exceptions.JSONDecodeError` to decrease inconsistencies10+ in the library. This gets raised in the `response.json()` method, and is11+ backwards compatible as it inherits from previously thrown exceptions.12+ Can be caught from `requests.exceptions.RequestException` as well.13+14 2.26.0 (2021-07-13)15 -------------------16 17 **Improvements**1739 unmodified lines