Add an exception for missing configuration sections

This commit is contained in:
Davis Goglin 2016-03-30 17:10:21 -07:00
parent 5ecae9d585
commit b9c9189ca7
2 changed files with 28 additions and 5 deletions

View File

@ -46,11 +46,15 @@ class Config(object):
)
try:
if isinstance(config_path, str):
# First check if it's file like. If it is, pyyaml can load it.
# I'm checking type instead of catching excpetions to keep the
# exception handling simple
if hasattr(config_path, 'read'):
config = yaml.safe_load(config_path)
else:
# If it isn't, it's a path. We have to open it first.
with open(config_path, 'rb') as config_file:
config = yaml.safe_load(config_file)
else:
config = yaml.safe_load(config_path)
except EnvironmentError:
raise exceptions.ConfigNotFoundError('Couldn\'t read config at {config_path}'.format(
config_path=str(config_path),
@ -72,7 +76,8 @@ class Config(object):
self._has_loaded = True
def printer(self):
""" Returns a printer that was defined in the config, or None.
""" Returns a printer that was defined in the config, or throws an
exception.
This method loads the default config if one hasn't beeen already loaded.
@ -80,6 +85,9 @@ class Config(object):
if not self._has_loaded:
self.load()
if not self._printer_name:
raise exceptions.ConfigSectionMissingError('printer')
if not self._printer:
# We could catch init errors and make them a ConfigSyntaxError,
# but I'll just let them pass

View File

@ -15,6 +15,7 @@ Result/Exit codes:
- `100` = Set variable out of range :py:exc:`~escpos.exceptions.SetVariableError`
- `200` = Configuration not found :py:exc:`~escpos.exceptions.ConfigNotFoundError`
- `210` = Configuration syntax error :py:exc:`~escpos.exceptions.ConfigSyntaxError`
- `220` = Configuration section not found :py:exc:`~escpos.exceptions.ConfigSectionMissingError`
:author: `Manuel F Martinez <manpaz@bashlinux.com>`_ and others
:organization: Bashlinux and `python-escpos <https://github.com/python-escpos>`_
@ -211,7 +212,7 @@ class ConfigNotFoundError(Error):
class ConfigSyntaxError(Error):
""" The configuration file is invalid
The syntax is incorrect or there is a section missing
The syntax is incorrect
Ths returncode for this exception is `210`.
"""
def __init__(self, msg=""):
@ -221,3 +222,17 @@ class ConfigSyntaxError(Error):
def __str__(self):
return "Configuration syntax is invalid ({msg})".format(msg=self.msg)
class ConfigSectionMissingError(Error):
""" The configuration file is missing a section
The part of the config asked for doesn't exist in the loaded configuration
Ths returncode for this exception is `220`.
"""
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 220
def __str__(self):
return "Configuration section is missing ({msg})".format(msg=self.msg)