refactored error management (sent raised errors to the error manager)

This commit is contained in:
vicky 2022-05-10 22:34:25 +02:00
parent c540c66f6f
commit 12bbc0bf3a
5 changed files with 31 additions and 20 deletions

View File

@ -1,6 +1,7 @@
# Interprets config files
import os
import yaml
from bootstraparse import error_mngr
class ConfigLoader:
@ -25,8 +26,8 @@ class ConfigLoader:
elif isinstance(config_folder, (list, tuple)):
self.config_folders = config_folder
else:
raise TypeError(f"Incorrect config type given. Expected a string, list or tuple; "
f"got {type(config_folder).__name__} instead.")
error_mngr.log_exception(TypeError(f"Incorrect config type given. Expected a string, list or tuple; "
f"got {type(config_folder).__name__} instead."), level='CRITICAL')
self.loaded_conf = {}
self.extensions = extensions
self.reload_all()
@ -63,9 +64,10 @@ class ConfigLoader:
self.loaded_conf[name] = yaml.safe_load(f)
else:
self.loaded_conf[name].update(yaml.safe_load(f))
print(f"Warning: {name} is already in {self.loaded_conf}")
error_mngr.log_message(f"Warning: {name} is already in {self.loaded_conf}", level='WARNING')
except yaml.parser.ParserError as e:
raise yaml.parser.ParserError(e) # TODO: make a custom error message
error_mngr.log_message(f'Error parsing in file {basename} at {filepath}.', level='CRITICAL')
error_mngr.log_exception(yaml.parser.ParserError(e), level='CRITICAL')
def load_from_folder(self, folder):
"""
@ -86,8 +88,7 @@ class ConfigLoader:
try:
return self.loaded_conf[item]
except KeyError:
print(f"Error: {item} is not in {self.loaded_conf}")
raise KeyError # TODO: add to error manager
error_mngr.log_exception(KeyError(f"Error: {item} is not in {self.loaded_conf}"), level='CRITICAL')
def __repr__(self):
"""

View File

@ -1,5 +1,5 @@
# Module for containing super important variables
from bootstraparse import error_mngr
class Environment:
"""
@ -52,7 +52,12 @@ class Environment:
elif attribute in self._sParams:
return self._sParams[attribute]
else:
raise AttributeError(attribute)
error_mngr.log_exception(AttributeError(
f'Attribute {attribute} not in mandatory, secondary or reserved parameters.'
f'\nMandatory parameters:\n{self._mParams}'
f'\nSecondary parameters:\n{self._sParams}'
f'\nReserved parameters are preceded with an underscore.'
), level='CRITICAL')
def __setattr__(self, attribute, value):
"""
@ -66,4 +71,9 @@ class Environment:
elif attribute in self._sParams:
self._sParams[attribute] = value
else:
raise AttributeError(attribute) # Could also add attribute as a new entry
error_mngr.log_exception(AttributeError(
f'Attribute {attribute} not in mandatory, secondary or reserved parameters.'
f'\nMandatory parameters:\n{self._mParams}'
f'\nSecondary parameters:\n{self._sParams}'
f'\nReserved parameters are preceded with an underscore.'
), level='CRITICAL') # Could also add attribute as a new entry

View File

@ -10,7 +10,7 @@ _ERRORS = ["ParsingError"]
__all__ = _ERRORS+[]
def initlogging(filename=None, loglevel="ERROR", filemode='w', handler=None):
def init_logging(filename=None, loglevel="ERROR", filemode='w', handler=None):
"""
Initializes logging
:param filename: The name of the log file
@ -60,10 +60,9 @@ def log_exception(exception, level="ERROR"):
"""
level = level.lower()
logging.__getattribute__(level)(traceback.format_exc())
if level in ["critical"]:
if level in ["critical", "error"]:
print("An unrecoverable error occurred, please check the log file for more information.")
sys.exit()
# raise exception # Re-raises the exception
sys.exit() # could also re-raise the exception
if exception.__class__.__name__ == "ParsingError":
logging.error(exception.__str__())

View File

@ -1,5 +1,4 @@
# Module for pre-parsing user files in preparation for the parser
import logging
import os
import regex
from io import StringIO
@ -7,7 +6,7 @@ from io import StringIO
from bootstraparse.modules import pathresolver as pr
from bootstraparse.modules import environment
from bootstraparse.modules import syntax
from bootstraparse.modules import error_mngr as em # noqa # pylint: disable=unused-import
from bootstraparse.modules import error_mngr # noqa # pylint: disable=unused-import
import rich
from rich.tree import Tree
@ -137,7 +136,9 @@ class PreParser:
for e, l in import_list:
if e in self.list_of_paths:
raise RecursionError("Error: {} was imported earlier in {}".format(e, self.list_of_paths))
error_mngr.log_exception(
RecursionError(f"Error: {e} was imported earlier in {self.list_of_paths}"), level='CRITICAL'
)
if e in self.global_dict_of_imports:
pp = self.global_dict_of_imports[e]
else:
@ -146,9 +147,9 @@ class PreParser:
self.global_dict_of_imports[e] = pp
pp.make_import_list()
except FileNotFoundError:
logging.error("The import {} in file {} line {} doesn't exist".format(e, self.name, l))
# TODO: raise a custom exception or define a default behaviour
raise ImportError("The import {} in file {} line {} doesn't exist".format(e, self.name, l))
error_mngr.log_exception(
ImportError("The import {} in file {} line {} doesn't exist".format(e, self.name, l))
)
self.local_dict_of_imports[e] = pp
self.is_global_dict_of_imports_initialized = True
return self.local_dict_of_imports

View File

@ -23,7 +23,7 @@ class TestLogging(TestCase):
def test_init_logging(self):
for filename, level, handler in all_logging_tests:
with self.assertLogs() as captured:
error_mngr.initlogging(filename=filename, loglevel=level, handler=handler)
error_mngr.init_logging(filename=filename, loglevel=level, handler=handler)
logging.critical("Logging initialized", exc_info=True)
self.assertEqual(len(captured.records), 1)
self.assertEqual(captured.records[0].levelname, "CRITICAL")