Skip to content

Commit 74d0a34

Browse files
author
vvcheremushkin
committed
add decode error
1 parent e7c0305 commit 74d0a34

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

star_resty/exceptions.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from marshmallow.exceptions import ValidationError
44

5+
__all__ = ('StarRestError', 'DumpError', 'DecodeError')
6+
57

68
class StarRestError(Exception):
79
pass
@@ -18,3 +20,9 @@ def normalized_messages(self) -> Dict:
1820
return self.orig_exc.normalized_messages()
1921

2022
return {'_schema': 'Error dump content'}
23+
24+
25+
class DecodeError(StarRestError):
26+
27+
def normalized_messages(self) -> Dict:
28+
return {'_body': str(self)}

star_resty/types/json.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import types
22
from typing import Mapping, Type, TypeVar, Union
33

4+
import ujson
45
from marshmallow import EXCLUDE, Schema
56
from starlette.requests import Request
67

8+
from star_resty.exceptions import DecodeError
79
from .parser import Parser, set_parser
810

911
__all__ = ('json_schema', 'json_payload')
@@ -32,8 +34,13 @@ def media_type(self):
3234
return 'application/json'
3335

3436
async def parse(self, request: Request):
35-
body = await request.json()
37+
body = await request.body()
3638
if body is None:
37-
body = {}
38-
39-
return self.schema.load(body, unknown=self.unknown)
39+
data = {}
40+
else:
41+
try:
42+
data = ujson.loads(body)
43+
except (TypeError, ValueError) as e:
44+
raise DecodeError('Invalid json body') from e
45+
46+
return self.schema.load(data, unknown=self.unknown)

tests/test_method.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
async def test_create_user():
1616
request = mock.MagicMock(spec_set=Request)
1717
request.path_params = {'id': 1}
18-
request.json.return_value = {'name': 'Name', 'email': '[email protected]'}
18+
request.body.return_value = json.dumps({'name': 'Name', 'email': '[email protected]'}).encode('utf8')
1919

2020
endpoint = CreateUser.as_endpoint()
2121
resp = await endpoint(request)

0 commit comments

Comments
 (0)