Catch all the exceptions in python JSON ParseDict and raise
json_format.ParseError PiperOrigin-RevId: 627794381pull/16579/head
parent
8be1312b3c
commit
9cc5be12ed
|
@ -1439,7 +1439,7 @@ class JsonFormatTest(JsonFormatBase):
|
||||||
def testInvalidAny(self):
|
def testInvalidAny(self):
|
||||||
message = any_pb2.Any()
|
message = any_pb2.Any()
|
||||||
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
|
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}'
|
text = '{"value": 1234}'
|
||||||
self.assertRaisesRegex(
|
self.assertRaisesRegex(
|
||||||
json_format.ParseError,
|
json_format.ParseError,
|
||||||
|
@ -1662,6 +1662,12 @@ class JsonFormatTest(JsonFormatBase):
|
||||||
json_format.Parse(json_string, new_parsed_message)
|
json_format.Parse(json_string, new_parsed_message)
|
||||||
self.assertEqual(new_message, 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__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
|
@ -451,13 +451,22 @@ def Parse(
|
||||||
"""
|
"""
|
||||||
if not isinstance(text, str):
|
if not isinstance(text, str):
|
||||||
text = text.decode('utf-8')
|
text = text.decode('utf-8')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
js = json.loads(text, object_pairs_hook=_DuplicateChecker)
|
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
|
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(
|
def ParseDict(
|
||||||
|
|
Loading…
Reference in New Issue