Skip to content

Commit

Permalink
Improvements to parser error handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
dharvey-consbio committed Oct 26, 2016
1 parent 34c9034 commit 9861892
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
9 changes: 6 additions & 3 deletions gis_metadata/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
""" A module to define custom exceptions """
""" A module to define metadata parsing exceptions """


class ParserError(Exception):
""" A class to encapsulate all parsing exceptions """

def __init__(self, msg_format, *args, **kwargs):
def __init__(self, msg_format, invalid=None, missing=None, **kwargs):
"""
Call Exception with a message formatted with named arguments from
a Dictionary with values by key, or a list of named parameters.
"""
Exception.__init__(self, msg_format.format(*args, **kwargs))

super(ParserError, self).__init__(msg_format.format(**kwargs))

# Track details about the error for handling downstream
self.invalid = {} if invalid is None else invalid
self.missing = [] if missing is None else missing
2 changes: 1 addition & 1 deletion gis_metadata/metadata_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def get_parsed_content(metadata_content):
if xml_tree is None:
raise ParserError(
'Cannot instantiate a {parser_type} parser with invalid content to parse',
parser_type=type(metadata_content)
parser_type=type(metadata_content).__name__
)

xml_root = get_element_name(xml_tree)
Expand Down
10 changes: 7 additions & 3 deletions gis_metadata/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,14 +639,17 @@ def validate_properties(props, required):
required = set(required or _supported_props)

if len(required.intersection(props)) < len(required):
raise ParserError('Missing property names: {props}', props=','.join(required - props))
missing = required - props
raise ParserError(
'Missing property names: {props}', props=','.join(missing), missing=missing
)


def validate_type(prop, value, expected):
""" Default validation for all types """

if not isinstance(value, expected):
_validation_error(prop, type(value), None, expected)
_validation_error(prop, type(value).__name__, None, expected)


def _validation_error(prop, prop_type, prop_value, expected):
Expand All @@ -661,7 +664,8 @@ def _validation_error(prop, prop_type, prop_value, expected):

raise ParserError(
'Invalid property {attrib} for {prop}:\n\t{attrib}: {assigned}\n\texpected: {expected}',
attrib=attrib, prop=prop, assigned=assigned, expected=expected
attrib=attrib, prop=prop, assigned=assigned, expected=expected,
invalid={prop: prop_value} if attrib == 'value' else {}
)


Expand Down

0 comments on commit 9861892

Please sign in to comment.