-
-
Save diraol/cd965996c07a012372f8c1027be1c5a1 to your computer and use it in GitHub Desktop.
Throw multiple validation errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block | |
class ValidationError(Exception): | |
def __init__(self, attribute_name, message): | |
self.attribute_name = attribute_name | |
self.message = message | |
def __str__(self): | |
return self.message | |
class ValidationErrors(ValidationError): | |
def __init__(self, errors*): | |
self.attributes = [] | |
self.messages = [] | |
for error in errors: | |
self.attributes.append(error.attribute_name) | |
self.messages.append(error.message) | |
def __str__(self): | |
message = '[' | |
message += '; '.join(str(a) for a in self.attributes) | |
message += ']' | |
# this is for attribute names as a string list | |
# return message | |
# | |
# this is for std error messages | |
return ' '.join(str(m) for m in self.messages) | |
e1 = ValidationError('AttributeA', 'Error 1.') | |
e2 = ValidationError('AttributeB', 'Error 2.') | |
# errors = [e1, e2] | |
raise ValidationErrors(e1, e2) | |
# Run and see "Error 1. Error 2." as error message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment