Skip to content

Commit 6940030

Browse files
authored
handle request decode errors (#37)
1 parent 53ca044 commit 6940030

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

twirp/base.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from collections import namedtuple
33

44
from google.protobuf import json_format
5+
from google.protobuf import message
56
from google.protobuf import symbol_database as _symbol_database
67

78

@@ -48,7 +49,13 @@ def _get_endpoint(self, path):
4849
@staticmethod
4950
def json_decoder(body, data_obj=None):
5051
data = data_obj()
51-
json_format.Parse(body, data)
52+
try:
53+
json_format.Parse(body, data)
54+
except json_format.ParseError as exc:
55+
raise exceptions.TwirpServerException(
56+
code=errors.Errors.Malformed,
57+
message="the json request could not be decoded",
58+
) from exc
5259
return data
5360

5461
@staticmethod
@@ -64,7 +71,13 @@ def json_encoder(value, data_obj=None):
6471
@staticmethod
6572
def proto_decoder(body, data_obj=None):
6673
data = data_obj()
67-
data.ParseFromString(body)
74+
try:
75+
data.ParseFromString(body)
76+
except message.DecodeError as exc:
77+
raise exceptions.TwirpServerException(
78+
code=errors.Errors.Malformed,
79+
message="the protobuf request could not be decoded",
80+
) from exc
6881
return data
6982

7083
@staticmethod
@@ -90,4 +103,4 @@ def _get_encoder_decoder(self, endpoint, headers):
90103
code=errors.Errors.BadRoute,
91104
message="unexpected Content-Type: " + ctype
92105
)
93-
return encoder, decoder
106+
return encoder, decoder

0 commit comments

Comments
 (0)