Skip to content

Commit 3667157

Browse files
authored
Merge pull request #145 from dotsbb/fix-too-broad-exception
Wrong error message "invalid JSON" when "RequestDataTooBig" raised
2 parents 7eb4106 + 33b2b42 commit 3667157

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

graphene_django/tests/test_views.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,21 @@ def test_handles_invalid_json_bodies(client):
457457
}
458458

459459

460+
def test_handles_django_request_error(client, monkeypatch):
461+
def mocked_read(*args):
462+
raise IOError("foo-bar")
463+
464+
monkeypatch.setattr("django.http.request.HttpRequest.read", mocked_read)
465+
466+
valid_json = json.dumps(dict(foo='bar'))
467+
response = client.post(url_string(), valid_json, 'application/json')
468+
469+
assert response.status_code == 400
470+
assert response_json(response) == {
471+
'errors': [{'message': 'foo-bar'}]
472+
}
473+
474+
460475
def test_handles_incomplete_json_bodies(client):
461476
response = client.post(url_string(), '{"query":', 'application/json')
462477

graphene_django/views.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,16 +179,21 @@ def json_encode(self, request, d, pretty=False):
179179
return json.dumps(d, sort_keys=True,
180180
indent=2, separators=(',', ': '))
181181

182-
# noinspection PyBroadException
183182
def parse_body(self, request):
184183
content_type = self.get_content_type(request)
185184

186185
if content_type == 'application/graphql':
187186
return {'query': request.body.decode()}
188187

189188
elif content_type == 'application/json':
189+
# noinspection PyBroadException
190190
try:
191-
request_json = json.loads(request.body.decode('utf-8'))
191+
body = request.body.decode('utf-8')
192+
except Exception as e:
193+
raise HttpError(HttpResponseBadRequest(str(e)))
194+
195+
try:
196+
request_json = json.loads(body)
192197
if self.batch:
193198
assert isinstance(request_json, list), (
194199
'Batch requests should receive a list, but received {}.'
@@ -203,7 +208,7 @@ def parse_body(self, request):
203208
return request_json
204209
except AssertionError as e:
205210
raise HttpError(HttpResponseBadRequest(str(e)))
206-
except:
211+
except (TypeError, ValueError):
207212
raise HttpError(HttpResponseBadRequest('POST body sent invalid JSON.'))
208213

209214
elif content_type in ['application/x-www-form-urlencoded', 'multipart/form-data']:

0 commit comments

Comments
 (0)