Skip to content

Commit

Permalink
handle request decode errors (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
chadawagner authored Feb 8, 2022
1 parent 53ca044 commit 6940030
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions twirp/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from collections import namedtuple

from google.protobuf import json_format
from google.protobuf import message
from google.protobuf import symbol_database as _symbol_database


Expand Down Expand Up @@ -48,7 +49,13 @@ def _get_endpoint(self, path):
@staticmethod
def json_decoder(body, data_obj=None):
data = data_obj()
json_format.Parse(body, data)
try:
json_format.Parse(body, data)
except json_format.ParseError as exc:
raise exceptions.TwirpServerException(
code=errors.Errors.Malformed,
message="the json request could not be decoded",
) from exc
return data

@staticmethod
Expand All @@ -64,7 +71,13 @@ def json_encoder(value, data_obj=None):
@staticmethod
def proto_decoder(body, data_obj=None):
data = data_obj()
data.ParseFromString(body)
try:
data.ParseFromString(body)
except message.DecodeError as exc:
raise exceptions.TwirpServerException(
code=errors.Errors.Malformed,
message="the protobuf request could not be decoded",
) from exc
return data

@staticmethod
Expand All @@ -90,4 +103,4 @@ def _get_encoder_decoder(self, endpoint, headers):
code=errors.Errors.BadRoute,
message="unexpected Content-Type: " + ctype
)
return encoder, decoder
return encoder, decoder

0 comments on commit 6940030

Please sign in to comment.