Search all modules for a matching exception

This commit is contained in:
2Shirt 2021-04-24 16:55:17 -06:00
parent 9a77a5cb9b
commit 005d4d1ea6
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C

View file

@ -18,6 +18,7 @@ import time
import traceback import traceback
from collections import OrderedDict from collections import OrderedDict
from functools import cache
import requests import requests
@ -498,24 +499,41 @@ class TryAndPrint():
# Done # Done
return result_msg return result_msg
@cache
def _get_exception(self, name): def _get_exception(self, name):
# pylint: disable=no-self-use # pylint: disable=no-self-use
"""Get exception by name, returns exception object. """Get exception by name, returns exception object.
[Doctest] [Doctest]
>>> self._get_exception('AttributeError') >>> t = TryAndPrint()
>>> t._get_exception('AttributeError')
<class 'AttributeError'> <class 'AttributeError'>
>>> self._get_exception('CalledProcessError') >>> t._get_exception('CalledProcessError')
<class 'subprocess.CalledProcessError'> <class 'subprocess.CalledProcessError'>
>>> self._get_exception('GenericError') >>> t._get_exception('GenericError')
<class 'std.GenericError'> <class 'wk.std.GenericError'>
""" """
LOG.debug('Getting exception: %s', name) LOG.debug('Getting exception: %s', name)
try: obj = getattr(sys.modules[__name__], name, None)
obj = getattr(sys.modules[__name__], name) if obj:
except AttributeError: return obj
# Try builtin classes
obj = getattr(sys.modules['builtins'], name) # Try builtin classes
obj = getattr(sys.modules['builtins'], name, None)
if obj:
return obj
# Try all modules
for _mod in sys.modules:
obj = getattr(sys.modules[_mod], name, None)
if obj:
break
# Check if not found
if not obj:
raise AttributeError(f'Failed to find exception: {name}')
# Done
return obj return obj
def _log_result(self, message, result_msg): def _log_result(self, message, result_msg):