Skip to content

Commit

Permalink
Merge pull request #78 from xsnippet/bad-request-on-malformed-json
Browse files Browse the repository at this point in the history
Return 400 Bad Request on malformed input JSON
  • Loading branch information
ikalnytskyi committed Mar 11, 2018
2 parents fe674f9 + dc3b694 commit 59353c1
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 59353c1

Please sign in to comment.