Catch all the exceptions in python JSON ParseDict and raise

json_format.ParseError

PiperOrigin-RevId: 627794381
pull/16579/head
Jie Luo 2024-04-24 11:27:29 -07:00 committed by Copybara-Service
parent 8be1312b3c
commit 9cc5be12ed
2 changed files with 20 additions and 5 deletions

View File

@ -1439,7 +1439,7 @@ class JsonFormatTest(JsonFormatBase):
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,
@ -1662,6 +1662,12 @@ class JsonFormatTest(JsonFormatBase):
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()

View File

@ -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(