diff --git a/restless/serializers.py b/restless/serializers.py index 89104ce..b372993 100644 --- a/restless/serializers.py +++ b/restless/serializers.py @@ -1,3 +1,4 @@ +from .exceptions import BadRequest from .utils import json, MoreTypesJSONEncoder @@ -58,9 +59,12 @@ def deserialize(self, body): :returns: The deserialized data :rtype: ``list`` or ``dict`` """ - if isinstance(body, bytes): - return json.loads(body.decode('utf-8')) - return json.loads(body) + try: + if isinstance(body, bytes): + return json.loads(body.decode('utf-8')) + return json.loads(body) + except ValueError: + raise BadRequest('Request body is not valid JSON') def serialize(self, data): """ diff --git a/tests/test_serializers.py b/tests/test_serializers.py index c765a35..2535376 100644 --- a/tests/test_serializers.py +++ b/tests/test_serializers.py @@ -3,6 +3,7 @@ import unittest import uuid +from restless.exceptions import BadRequest from restless.serializers import JSONSerializer @@ -33,3 +34,7 @@ def test_deserialize(self): self.assertEqual(self.serializer.deserialize('{"more": "things"}'), { 'more': 'things', }) + + def test_deserialize_invalid(self): + with self.assertRaises(BadRequest): + self.serializer.deserialize('not valid!')