Skip to content

Commit

Permalink
Adding error codes to errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jespino committed Mar 18, 2015
1 parent 7f8ea26 commit 376d214
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 4 deletions.
3 changes: 2 additions & 1 deletion skame/exceptions.py
Expand Up @@ -9,5 +9,6 @@ def __init__(self, error, error_code="invalid"):
class SchemaErrors(Exception):
"""Exception used to indicate that the validation of multiple values failed."""

def __init__(self, errors):
def __init__(self, errors, error_codes):
self.errors = errors
self.error_codes = error_codes
7 changes: 5 additions & 2 deletions skame/schemas/base.py
Expand Up @@ -200,6 +200,7 @@ def __init__(self, mapping: dict):

def _validate(self, data: dict, fields: dict, value_getter: "function") -> dict:
errors = {}
error_codes = {}
result = {}

for field in fields:
Expand All @@ -208,13 +209,15 @@ def _validate(self, data: dict, fields: dict, value_getter: "function") -> dict:
cleaned_value = self.mapping[field].validate(value)
except KeyError:
errors[str(field)] = _("Field `{0}` is required.").format(field)
error_codes[str(field)] = "required"
except SchemaError as e:
errors[str(field)] = e.error
error_codes[str(field)] = e.error_code
else:
result[str(field)] = cleaned_value

if errors:
raise SchemaErrors(errors)
if errors or error_codes:
raise SchemaErrors(errors, error_codes)

return result

Expand Down
1 change: 1 addition & 0 deletions skame/schemas/strings.py
Expand Up @@ -23,6 +23,7 @@ def validate(self, data: object) -> object:
return data


# Based on django validators code
class EmailSchema(Schema):
"""Validator for checking if a value is an email."""
message = _("Invalid email format")
Expand Down
2 changes: 1 addition & 1 deletion skame/validator.py
Expand Up @@ -10,7 +10,7 @@ def clean_data_or_raise(schema: "Schema", data: dict, exc_type: "Exception"=Sche
try:
return schema.validate(data)
except SchemaErrors as e:
raise exc_type(e.errors)
raise exc_type(e.errors, e.error_codes)


def validate(schema: "Schema", data: dict) -> (dict, dict):
Expand Down

0 comments on commit 376d214

Please sign in to comment.