Skip to content

Commit 9cc5be1

Browse files
anandoleecopybara-github
authored andcommitted
Catch all the exceptions in python JSON ParseDict and raise
json_format.ParseError PiperOrigin-RevId: 627794381
1 parent 8be1312 commit 9cc5be1

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

python/google/protobuf/internal/json_format_test.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1439,7 +1439,7 @@ def testFieldMaskInvalidStringValue(self):
14391439
def testInvalidAny(self):
14401440
message = any_pb2.Any()
14411441
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
1442-
self.assertRaisesRegex(KeyError, 'value', json_format.Parse, text, message)
1442+
self.assertRaisesRegex(json_format.ParseError, 'KeyError: \'value\'', json_format.Parse, text, message)
14431443
text = '{"value": 1234}'
14441444
self.assertRaisesRegex(
14451445
json_format.ParseError,
@@ -1662,6 +1662,12 @@ def testJsonNameConflictRoundTrip(self):
16621662
json_format.Parse(json_string, new_parsed_message)
16631663
self.assertEqual(new_message, new_parsed_message)
16641664

1665+
def testOtherParseErrors(self):
1666+
self.CheckError(
1667+
'9',
1668+
"Failed to parse JSON: TypeError: 'int' object is not iterable.",
1669+
)
1670+
16651671

16661672
if __name__ == '__main__':
16671673
unittest.main()

python/google/protobuf/json_format.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -451,13 +451,22 @@ def Parse(
451451
"""
452452
if not isinstance(text, str):
453453
text = text.decode('utf-8')
454+
454455
try:
455456
js = json.loads(text, object_pairs_hook=_DuplicateChecker)
456-
except ValueError as e:
457+
except Exception as e:
457458
raise ParseError('Failed to load JSON: {0}.'.format(str(e))) from e
458-
return ParseDict(
459-
js, message, ignore_unknown_fields, descriptor_pool, max_recursion_depth
460-
)
459+
460+
try:
461+
return ParseDict(
462+
js, message, ignore_unknown_fields, descriptor_pool, max_recursion_depth
463+
)
464+
except ParseError as e:
465+
raise e
466+
except Exception as e:
467+
raise ParseError(
468+
'Failed to parse JSON: {0}: {1}.'.format(type(e).__name__, str(e))
469+
) from e
461470

462471

463472
def ParseDict(

0 commit comments

Comments
 (0)