From c1a7079c26d27a2e46cca26963d3d9aa040bdbe8 Mon Sep 17 00:00:00 2001 From: "John L. Villalovos" Date: Thu, 28 Sep 2017 13:03:12 -0700 Subject: [PATCH] When serializing an exception return its 'repr' When serializing an exception return its 'repr'. A 'repr' is a printable representation of an object. For example the exception: ValueError("an exception") will be returned as the string: "ValueError('an exception',)" Change-Id: Iac9f4624bcc4ff65e27c9ca20c6cbbe9481cf334 --- oslo_serialization/jsonutils.py | 4 ++++ oslo_serialization/tests/test_jsonutils.py | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/oslo_serialization/jsonutils.py b/oslo_serialization/jsonutils.py index e53ef4a..3578f87 100644 --- a/oslo_serialization/jsonutils.py +++ b/oslo_serialization/jsonutils.py @@ -132,6 +132,10 @@ def to_primitive(value, convert_instances=False, convert_datetime=True, ipaddress.IPv6Address)): return six.text_type(value) + # For exceptions, return the 'repr' of the exception object + if isinstance(value, Exception): + return repr(value) + # value of itertools.count doesn't get caught by nasty_type_tests # and results in infinite loop when list(value) is called. if type(value) == itertools.count: diff --git a/oslo_serialization/tests/test_jsonutils.py b/oslo_serialization/tests/test_jsonutils.py index 8badebd..da8edd4 100644 --- a/oslo_serialization/tests/test_jsonutils.py +++ b/oslo_serialization/tests/test_jsonutils.py @@ -115,6 +115,10 @@ class JSONUtilsTestMixin(object): self.assertIsInstance(key, six.text_type) self.assertIsInstance(val, six.text_type) + def test_dumps_exception_value(self): + self.assertEqual('{"a": "ValueError(\'hello\',)"}', + jsonutils.dumps({"a": ValueError("hello")})) + class JSONUtilsTestJson(JSONUtilsTestMixin, test_base.BaseTestCase): json_impl = json @@ -401,3 +405,7 @@ class ToPrimitiveTestCase(test_base.BaseTestCase): ret = jsonutils.to_primitive(obj, fallback=lambda _: 'fallback') self.assertEqual('fallback', ret) + + def test_exception(self): + self.assertEqual("ValueError('an exception',)", + jsonutils.to_primitive(ValueError("an exception")))