Skip to content

Commit 42b1864

Browse files
committed
Initialize JsonDecodeError before initializing IOError
That way we get the formated error message
1 parent 620ed4f commit 42b1864

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

requests/exceptions.py

+10
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@ class InvalidJSONError(RequestException):
3434
class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
3535
"""Couldn't decode the text into json"""
3636

37+
def __init__(self, *args, **kwargs):
38+
"""
39+
Construct the JSONDecodeError instance first with all
40+
args. Then use it's args to construct the IOError so that
41+
the json specific args aren't used as IOError specific args
42+
and the error message from JSONDecodeError is preserved
43+
"""
44+
CompatJSONDecodeError.__init__(self, *args)
45+
InvalidJSONError.__init__(self, *self.args, **kwargs)
46+
3747

3848
class HTTPError(RequestException):
3949
"""An HTTP error occurred."""

tests/test_requests.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@
2323
cookiejar_from_dict, morsel_to_cookie)
2424
from requests.exceptions import (
2525
ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,
26-
MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,
26+
MissingSchema, ReadTimeout, Timeout, RetryError, RequestException, TooManyRedirects,
2727
ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL, InvalidJSONError)
2828
from requests.models import PreparedRequest
2929
from requests.structures import CaseInsensitiveDict
3030
from requests.sessions import SessionRedirectMixin
3131
from requests.models import urlencode
3232
from requests.hooks import default_hooks
33-
from requests.compat import MutableMapping
33+
from requests.compat import JSONDecodeError, is_py3, MutableMapping
3434

3535
from .compat import StringIO, u
3636
from .utils import override_environ
@@ -2585,5 +2585,11 @@ def test_post_json_nan(self, httpbin):
25852585

25862586
def test_json_decode_compatibility(self, httpbin):
25872587
r = requests.get(httpbin('bytes/20'))
2588-
with pytest.raises(requests.exceptions.JSONDecodeError):
2588+
data = r.text
2589+
with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
25892590
r.json()
2591+
assert isinstance(excinfo.value, RequestException)
2592+
assert isinstance(excinfo.value, JSONDecodeError)
2593+
assert data not in str(excinfo.value)
2594+
if is_py3:
2595+
assert excinfo.value.doc == data

0 commit comments

Comments
 (0)