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
This commit is contained in:
John L. Villalovos 2017-09-28 13:03:12 -07:00
parent cdb2f60d26
commit c1a7079c26
2 changed files with 12 additions and 0 deletions

View File

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

View File

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