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")))