diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py index 6c5a5e32c8..965557eb1e 100644 --- a/python/google/protobuf/internal/json_format_test.py +++ b/python/google/protobuf/internal/json_format_test.py @@ -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() diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py index 8a2e24975b..2a6bba9391 100644 --- a/python/google/protobuf/json_format.py +++ b/python/google/protobuf/json_format.py @@ -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(