Skip to content

Commit

Permalink
Catch all the exceptions in python JSON ParseDict and raise
Browse files Browse the repository at this point in the history
json_format.ParseError

PiperOrigin-RevId: 627794381
  • Loading branch information
anandolee authored and copybara-github committed Apr 24, 2024
1 parent 8be1312 commit 9cc5be1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
8 changes: 7 additions & 1 deletion python/google/protobuf/internal/json_format_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ def testFieldMaskInvalidStringValue(self):
def testInvalidAny(self):
message = any_pb2.Any()
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
self.assertRaisesRegex(KeyError, 'value', json_format.Parse, text, message)
self.assertRaisesRegex(json_format.ParseError, 'KeyError: \'value\'', json_format.Parse, text, message)
text = '{"value": 1234}'
self.assertRaisesRegex(
json_format.ParseError,
Expand Down Expand Up @@ -1662,6 +1662,12 @@ def testJsonNameConflictRoundTrip(self):
json_format.Parse(json_string, new_parsed_message)
self.assertEqual(new_message, new_parsed_message)

def testOtherParseErrors(self):
self.CheckError(
'9',
"Failed to parse JSON: TypeError: 'int' object is not iterable.",
)


if __name__ == '__main__':
unittest.main()
17 changes: 13 additions & 4 deletions python/google/protobuf/json_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,13 +451,22 @@ def Parse(
"""
if not isinstance(text, str):
text = text.decode('utf-8')

try:
js = json.loads(text, object_pairs_hook=_DuplicateChecker)
except ValueError as e:
except Exception as e:
raise ParseError('Failed to load JSON: {0}.'.format(str(e))) from e
return ParseDict(
js, message, ignore_unknown_fields, descriptor_pool, max_recursion_depth
)

try:
return ParseDict(
js, message, ignore_unknown_fields, descriptor_pool, max_recursion_depth
)
except ParseError as e:
raise e
except Exception as e:
raise ParseError(
'Failed to parse JSON: {0}: {1}.'.format(type(e).__name__, str(e))
) from e


def ParseDict(
Expand Down

0 comments on commit 9cc5be1

Please sign in to comment.