inveniosoftware / flask-resources

REST APIs for Flask
https://flask-resources.readthedocs.io
MIT License
3 stars 21 forks source link

errors: review `SchemaValidationError` exception #69

Open zzacharo opened 4 years ago

zzacharo commented 4 years ago

The data validation should not be bound to Marshmallow. Invenio-records-resources allows you to define your own custom validation. In addition, we should probably define the exception as part of the invenio-records-resources.errors as that is the place the validation concept is defined.

ppanero commented 4 years ago

And any other invenio/resources related exceptions (e.g. FieldsError)

zzacharo commented 4 years ago

The SchemaValidationError exception code was deleted from the module and should be added in the invenio-records-resources. For reference, the deleted code:


class SchemaValidationError(HTTPJSONException):
    """Marshmallow schema validation exception."""

    def __init__(self, errors=None, **kwargs):
        """Initialize exception."""
        _errors = []
        if errors:
            for field, messages in errors.items():
                _errors.extend([_FieldError(field, msg) for msg in messages])
        super(SchemaValidationError, self).__init__(errors=_errors, **kwargs)

    class _FieldError(object):
        """Represents a field level error.

        .. note:: This is not an actual exception.
        """

        def __init__(self, field, message, code=None):
            """Init object.

            :param field: Field name.
            :param message: The text message to show.
            :param code: The HTTP status to return. (Default: ``None``)
            """
            self.res = dict(field=field, message=message)
            if code:
                self.res["code"] = code

        def to_dict(self):
            """Convert to dictionary.

            :returns: A dictionary with field, message and, if initialized, the
                HTTP status code.
            """
            return self.res

    def get_errors(self):
        """Get errors.

        :returns: A list containing a dictionary representing the errors.
        """
        return [e.to_dict() for e in self.errors] if self.errors else None