Skip to content

Commit

Permalink
Return 400 Bad Request on malformed input JSON
Browse files Browse the repository at this point in the history
Apparently we didn't have tests for malformed input payload and used to
fall with 500 Internal Server Error if input payload is not
de-serializable. o_O Luckily we found it early and from now on we will
return 400 Bad Request in this case.
  • Loading branch information
ikalnytskyi committed Mar 11, 2018
1 parent 67cd125 commit 8572053
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 10 additions & 0 deletions tests/test_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ async def test_post_json(testapp, headers):
assert await resp.json() == {'who': 'batman'}


async def test_post_malformed_payload(testapp):
resp = await testapp.post('/test', data='malformed')

assert resp.status == 400
assert await resp.json() == {
'message': ('Malformed application/json payload: '
'Expecting value: line 1 column 1 (char 0)'),
}


async def test_post_unsupported_media_type(testapp):
resp = await testapp.post(
'/test',
Expand Down
8 changes: 7 additions & 1 deletion xsnippet/api/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,13 @@ async def impl(self):

if content_type in decoders:
decode = decoders[content_type]
return decode(await self.text())
text = await self.text()

try:
return decode(text)
except Exception as exc:
raise web.HTTPBadRequest(
reason='Malformed %s payload: %s' % (content_type, exc))

raise web.HTTPUnsupportedMediaType()
return impl

0 comments on commit 8572053

Please sign in to comment.