Skip to content

Commit

Permalink
ENH: Allow exceptions to pass into convert_exception_to_primitives
Browse files Browse the repository at this point in the history
  • Loading branch information
cortadocodes committed Jun 9, 2024
1 parent 6c2702c commit d574b5a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
14 changes: 11 additions & 3 deletions octue/utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ def create_exceptions_mapping(*sources):
return exceptions_mapping


def convert_exception_to_primitives():
"""Convert an exception into a dictionary of its type, message, and traceback as JSON-serialisable primitives.
def convert_exception_to_primitives(exception=None):
"""Convert an exception into a dictionary of its type, message, and traceback as JSON-serialisable primitives. The
exception is acquired using `sys.exc_info` if one is not supplied.
:param Exception|None exception: the exception to convert; if `None`, the exception is acquired using `sys.exc_info`
:return dict: a dictionary with "type", "message" and "traceback" keys and JSON-serialisable values
"""
exception_info = sys.exc_info()
if exception:
try:
raise exception
except Exception:
exception_info = sys.exc_info()
else:
exception_info = sys.exc_info()

return {
"type": exception_info[0].__name__,
Expand Down
29 changes: 29 additions & 0 deletions tests/utils/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import unittest

from octue.utils.exceptions import convert_exception_to_primitives


class TestExceptions(unittest.TestCase):
def test_with_caught_exception(self):
"""Test converting a caught exception (without passing the exception directly)."""
try:
raise ValueError("Deliberately raised for test.")
except Exception:
converted_exception = convert_exception_to_primitives()

self.assertEqual(converted_exception["type"], "ValueError")
self.assertEqual(converted_exception["message"], "Deliberately raised for test.")

self.assertIn(
'in test_with_raised_exception\n raise ValueError("Deliberately raised for test.")',
converted_exception["traceback"][0],
)

def test_with_passed_unraised_exception(self):
"""Test converting an unraised exception passed in to the function."""
exception = ValueError("Deliberately raised for test.")
converted_exception = convert_exception_to_primitives(exception)

self.assertEqual(converted_exception["type"], "ValueError")
self.assertEqual(converted_exception["message"], "Deliberately raised for test.")
self.assertIn("in convert_exception_to_primitives\n raise exception", converted_exception["traceback"][0])

0 comments on commit d574b5a

Please sign in to comment.