Return an error message that is easier to read and more useful.
    May require updating if the schemas change significantly.
181364
def pretty_error(error, verbose=False):
    
    error_loc = ''

    if error.path:
        while len(error.path) > 0:
            path_elem = error.path.popleft()
            if type(path_elem) is not int:
                if error_loc:
                    error_loc += '.'
                error_loc += path_elem
            # elif len(error.path) > 0:
            else:
                error_loc += '[' + text_type(path_elem) + ']'
        error_loc += ': '

    # Get error message and remove ugly u'' prefixes
    if verbose:
        msg = remove_u(text_type(error))
    else:
        msg = remove_u(error.message)

    # Don't reword error messages from our validators,
    # only the default error messages from the jsonschema library
    if repr(error.schema) == '<unset>':
        try:
            return error_loc + msg
        except UnicodeDecodeError:
            return error_loc + msg.decode('utf-8')

    # Reword error messages containing regexes
    if error.validator == 'pattern' and 'title' in error.schema:
        if error.schema['title'] == 'type':
            msg = re.sub(r"match '.+'$", 'match the \'type\' field format '
                         '(lowercase ASCII a-z, 0-9, and hypens only - and no '
                         'two hyphens in a row)', msg)
        elif error.schema['title'] == 'identifier':
            msg = re.sub(r"match '.+'$", 'match the id format '
                         '([object-type]--[UUIDv4])', msg)
        elif error.schema['title'] == 'id':
            msg = re.sub(r"match '.+'$", 'start with \'' +
                         error.validator_value[1:-2] + '--\'', msg)
        elif error.schema['title'] == 'timestamp':
            msg = re.sub(r"match '.+'$", 'match the timestamp format '
                         'YYYY-MM-DDTHH:mm:ss[.s+]Z', msg)
        elif error.schema['title'] == 'timestamp_millis':
            msg = re.sub(r"match '.+'$", 'match the timestamp format '
                         'YYYY-MM-DDTHH:mm:ss.sssZ (must be precise to the '
                         'millisecond)', msg)
        elif error.schema['title'] == 'relationship_type':
            msg = re.sub(r"does not match '.+'$", 'contains invalid '
                         'characters', msg)
        elif error.schema['title'] == 'url-regex':
            msg = re.sub(r'match ".+"$', 'match the format '
                         'of a URL', msg)
        elif error.schema['title'] == 'binary':
            msg = re.sub(r"does not.+'$", 'must be a base64-encoded string', msg)
    elif error.validator == 'pattern' and 'observed_data_refs' in error.schema_path:
        msg = "'observed_data_refs' must refer to Observed Data Objects"
    elif error.validator == 'pattern' and 'where_sighted_refs' in error.schema_path:
        msg = "'where_sighted_refs' must refer to Identity Objects"

    # Reword empty array errors
    elif type(error.instance) is list and len(error.instance) == 0:
        msg = re.sub(r"\[\] is not valid .+$", 'empty arrays are not allowed',
                     msg)

    # Reword custom property errors
    elif 'title' in error.schema and error.schema['title'] == 'core':
        if error.validator == 'additionalProperties':
            msg = re.sub(r"Additional .+$", 'Custom properties must match the '
                         'proper format (lowercase ASCII a-z, 0-9, and '
                         'underscores; 3-250 characters)', msg)
        elif error.validator == 'not' and 'anyOf' in error.validator_value:
            reserved_properties = [y for x in error.validator_value['anyOf'] for y in x['required']]
            msg = re.sub(r".+", "Contains a reserved property ('%s')"
                         % "', '".join(reserved_properties), msg)
    elif 'title' in error.schema and error.schema['title'] == 'cyber-observable-core':
        if error.validator == 'additionalProperties':
            msg = re.sub(r"Additional .+$", 'Custom observable properties must'
                         ' match the proper format (lowercase ASCII a-z, 0-9, '
                         'and underscores; 3-250 characters)', msg)

    elif error.validator == 'additionalProperties':
        if 'extensions' in error.schema_path:
            msg = re.sub(r"Additional .+$", 'Custom extension keys may only '
                         'contain alphanumeric characters, dashes, and '
                         'underscores; 3-256 characters', msg)

    # Reword 'is valid under each of' errors
    elif error.validator == 'oneOf':
        try:
            if 'external_references' in error.schema_path:
                msg = "If the external reference is a CVE, 'source_name' must be" \
                      " 'cve' and 'external_id' must be in the CVE format " \
                      "(CVE-YYYY-NNNN+). If the external reference is a CAPEC, " \
                      "'source_name' must be 'capec' and 'external_id' must be " \
                      "in the CAPEC format (CAPEC-N+). If the external reference "\
                      "is neither, it must contain the 'source_name' property and"\
                      " at least one of the 'external_id', 'url', or "\
                      "'description' properties."
            elif 'type' in error.instance and error.instance['type'] == 'email-message':
                if 'is_multipart' not in error.instance:
                    msg = "'is_multipart' is a required property"
                elif error.instance['is_multipart'] is True:
                    msg = "Since 'is_multipart' is true, 'body_multipart' must "\
                          "contain valid 'mime-part-type' objects and the 'body' "\
                          "property must not be present. "
                elif error.instance['is_multipart'] is False:
                    msg = "Since 'is_multipart' is false, 'body' must be a string"\
                          " and the 'body_multipart' property must not be present."
            elif 'type' in error.instance and error.instance['type'] == 'artifact':
                if 'payload_bin' in error.instance and 'url' in error.instance:
                    msg = "'artifact' object must contain either 'payload_bin' "\
                          "or 'url' but not both"
                elif 'payload_bin' in error.instance:
                    msg = "'payload_bin' must be base64 encoded and 'hashes', if "\
                          "present, must contain a valid dictionary of hashes"
                elif 'url' in error.instance:
                    msg = "'url' must be a valid url and 'hashes', which must be "\
                          "present, must contain a valid hash dictionary"
                else:
                    msg = "'artifact' object must contain either 'payload_bin' "\
                          "or 'url'"
            elif 'type' in error.instance and error.instance['type'] == 'marking-definition':
                msg = "'definition' must contain a valid statement, TLP, or "\
                      "custom marking definition"
            elif 'type' in error.instance and error.instance['type'] == 'file':
                if (('is_encrypted' not in error.instance or
                        error.instance['is_encrypted'] is False) and
                        ('encryption_algorithm' in error.instance or
                         'decryption_key' in error.instance)):
                    msg = "'file' objects may only contain 'encryption_algorithm'"\
                          " or 'decryption_key' when 'is_encrypted' is true"
            elif 'type' in error.instance and error.instance['type'] == 'network-traffic':
                if ('is_active' in error.instance and
                        error.instance['is_active'] is True and
                        'end' in error.instance):
                    msg = "If the 'is_active' property is true, then the "\
                          "'end' property must not be included."
            else:
                raise TypeError
        except TypeError:
            msg = msg + ':\n' + remove_u(text_type(error.schema))

    # reword forbidden property or value errors
    elif error.validator == 'not':
        if 'enum' in error.validator_value:
            msg = re.sub(r"\{.+\} is not allowed for '(.+)'$", r"'\g<1>' is "
                         "not an allowed value", msg)
        elif ('target_ref' in error.schema_path or
              'source_ref' in error.schema_path):
                msg = "Relationships cannot link bundles, marking definitions"\
                      ", sightings, or other relationships. This field must "\
                      "contain the id of an SDO."
        elif 'sighting_of_ref' in error.schema_path:
            msg = "'sighting_of_ref' must refer to a STIX Domain Object or "\
                  "Custom Object"

    # Reword 'is not valid under any of the given schemas' errors
    elif error.validator == 'anyOf':
        try:
            if error.instance == {}:
                msg = "must contain at least one property from this type."
            elif error.instance is None:
                msg = "null properties are not allowed in STIX."
            elif 'type' in error.instance and error.instance['type'] == 'network-traffic':
                if ('src_ref' not in error.instance and
                        'dst_ref' not in error.instance):
                    msg = "'network-traffic' objects must contain at least "\
                          "one of 'src_ref' or 'dst_ref'"
            elif 'type' in error.instance and error.instance['type'] in ['process', 'x509-certificate']:
                if error.instance.keys() == ['type']:
                    msg = "must contain at least one property (other than `type`) from this object."
            else:
                raise TypeError
        except TypeError:
            msg = msg + ':\n' + remove_u(text_type(error.schema))

    return error_loc + msg
1270344
def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None:
        
        for error in errors:
            self._error_cache.add(error)
853759
def lazy_display_error(self, filename):
        """"""
        position = self.cursor()
        error = self.get_error_at(position)
        if error:
            report = error.get_truncated_message(position, self.width() - 1)
            self.raw_message(report)
1313378
void compareRecordTypes(Schema oldSchema,
                                                 Schema newSchema,
                                                 List<Message> messages,
                                                 String name) {
        if(oldSchema == null || newSchema == null || oldSchema.getType() != Schema.Type.RECORD) {
            throw new IllegalArgumentException("Old schema must be RECORD type. Name=" + name
                                               + ". Type=" + oldSchema);
        }

        if(newSchema.getType() != Schema.Type.RECORD) {
            messages.add(new Message(Level.ERROR, "Illegal type change from " + oldSchema.getType()
                                                  + " to " + newSchema.getType() + " for field "
                                                  + name));
            return;
        }

        // Check all of the fields in the new schema
        for(Field newField: newSchema.getFields()) {
            String fieldName = newField.name();
            Field oldField = oldSchema.getField(fieldName);

            if(oldField == null) {
                // This is a new field that did not exist in the original
                // schema.
                // Check if it is optional or has a default value.
                if(isOptional(newField)) {
                    if(newField.defaultValue() == null) {
                        messages.add(new Message(Level.INFO, "Added optional field " + name + "."
                                                             + fieldName
                                                             + " with no default value."));
                    } else {
                        messages.add(new Message(Level.INFO, "Added optional field " + name + "."
                                                             + fieldName + " with default value: "
                                                             + newField.defaultValue()));
                    }
                } else {
                    if(newField.defaultValue() == null) {
                        messages.add(new Message(Level.ERROR, "Added required field " + name + "."
                                                              + fieldName
                                                              + " with no default value."));
                    } else {
                        messages.add(new Message(Level.INFO, "Added required field " + name + "."
                                                             + fieldName + " with default value: "
                                                             + newField.defaultValue()));
                    }
                }
            } else {
                // This is a field that existed in the original schema.

                // Check if the field was changed from optional to required or
                // vice versa.
                boolean newFieldIsOptional = isOptional(newField);
                boolean oldFieldIsOptional = isOptional(oldField);

                if(oldFieldIsOptional != newFieldIsOptional) {
                    if(oldFieldIsOptional) {
                        messages.add(new Message(Level.ERROR,
                                                 "Existing field " + name + "." + fieldName
                                                         + " was optional and is now required."));
                    } else {
                        messages.add(new Message(Level.WARN, "Existing field " + name + "."
                                                             + fieldName
                                                             + " was required and is now optional."));
                    }
                }

                // Recursively compare the nested field types
                compareTypes(oldField.schema(), newField.schema(), messages, name + "." + fieldName);

                // Check if the default value has been changed
                if(newField.defaultValue() == null) {
                    if(oldField.defaultValue() != null) {
                        messages.add(new Message(Level.WARN,
                                                 "Removed default value for existing field " + name
                                                         + "." + fieldName
                                                         + ". The old default was: "
                                                         + oldField.defaultValue()));
                    }
                } else // newField.defaultValue() != null
                {
                    if(oldField.defaultValue() == null) {
                        messages.add(new Message(Level.WARN,
                                                 "Added a default value for existing field " + name
                                                         + "." + fieldName
                                                         + ". The new default is: "
                                                         + newField.defaultValue()));
                    } else if(!newField.defaultValue().equals(oldField.defaultValue())) {
                        messages.add(new Message(Level.INFO,
                                                 "Changed the default value for existing field "
                                                         + name + "." + fieldName
                                                         + ". The old default was: "
                                                         + oldField.defaultValue()
                                                         + ". The new default is: "
                                                         + newField.defaultValue()));
                    }
                }
            }

            // For all fields in the new schema (whether or not it existed in
            // the old schema), if there is a default value for this field, make
            // sure it is legal.
            if(newField.defaultValue() != null) {
                checkDefaultValueIsLegal(newField, messages, name + "." + fieldName);
            }
        }

        // Check if any fields were removed.
        for(Field oldField: newSchema.getFields()) {
            String fieldName = oldField.name();
            Field newField = newSchema.getField(fieldName);

            if(newField == null) {
                if(isOptional(oldField)) {
                    messages.add(new Message(Level.INFO, "Removed optional field " + name + "."
                                                         + fieldName));
                } else {
                    messages.add(new Message(Level.WARN, "Removed required field " + name + "."
                                                         + fieldName));
                }
            }
        }

        // Check if indexing was modified or added to any old fields.
        for(Field oldField: oldSchema.getFields()) {
            if(newSchema.getField(oldField.name()) != null) {
                String oldIndexType = oldField.getProp("indexType");
                String newIndexType = newSchema.getField(oldField.name()).getProp("indexType");

                // Check if added indexing.
                if(oldIndexType == null && newIndexType != null) {
                    messages.add(new Message(Level.ERROR,
                                             "Cannot add indexing to "
                                                     + oldField.name()
                                                     + ". Adding indexing to fields created without indexing is not supported."));
                }

                // Check if changed indexing
                if(oldIndexType != null && !oldIndexType.equals(newIndexType)) {
                    messages.add(new Message(Level.ERROR,
                                             "Cannot change indexing from "
                                                     + oldIndexType
                                                     + " to "
                                                     + newIndexType
                                                     + " for "
                                                     + oldField.name()
                                                     + ". Changing indexing method is not supported."));
                }
            }
        }
    }
206244
def _validated(self, data):
        """"""
        errors = []
        for sub in self.schemas:
            try:
                return sub(data)
            except NotValid as ex:
                errors.extend(ex.args)

        raise NotValid(' and '.join(errors))
1055550
def validate(schema, value, noun='value'):
    
    errors = schema.errors(value)
    if errors:
        error_details = ''
        for error in errors:
            if error.pointer:
                error_details += '  - %s: %s\n' % (error.pointer, error.message)
            else:
                error_details += '  - %s\n' % error.message
        raise ValidationError('Invalid %s:\n%s' % (noun, error_details))
167711
def onerror(self, message, source, lineno, colno):
        """"""
        return (message, source, lineno, colno)
239598
def errors(request, *args, **kwargs):
    
    search_term = request.GET.get('q', None)
    if '400' in search_term:
        return HttpResponseBadRequest(MESSAGE_400)
    elif '403' in search_term:
        return HttpResponseForbidden(MESSAGE_403)
    elif '404' in search_term:
        return HttpResponseNotFound(MESSAGE_404)
    elif '405' in search_term:
        return HttpResponseNotAllowed(['PATCH'], MESSAGE_405)
    return HttpResponseServerError(MESSAGE_500)
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
1232860
def schema_helper(self, name, _, schema=None, **kwargs):
        
        if schema is None:
            return None

        schema_instance = resolve_schema_instance(schema)

        schema_key = make_schema_key(schema_instance)
        self.warn_if_schema_already_in_spec(schema_key)
        self.openapi.refs[schema_key] = name

        json_schema = self.openapi.schema2jsonschema(schema_instance)

        return json_schema
435189
def raise_error(self, message='', errors=None, field_name=None):
        
        field_name = field_name if field_name else self.field_name
        raise ValidationError(message, errors=errors, field_name=field_name)
781331
def set_errors(self, result):
        

        # todo: use wtf locale
        errors = result.get_messages()

        for property_name in errors:
            if not hasattr(self, property_name):
                continue # ignore errors for missing fields

            prop_errors = errors[property_name]
            if type(prop_errors) is not list:
                prop_errors = ['<Nested schema result following...>']
            if property_name in self.errors:
                self.errors[property_name].extend(prop_errors)
            else:
                self.errors[property_name] = prop_errors
136563
def generate_error_message(tag, err_uniq, err_appl, err_mult):
    
    err = []
    if err_uniq:
        err.append('Uniqueness restriction: item type %s' % tag.item_type)
    if err_appl:
        err.append('Applicability restriction: field %s' % tag.field)
    if err_mult:
        err.append('Multiplicity restriction: field %s' % tag.field)
    return err
571156
def error(self, message: str) -> None:
        """"""
        if len(self._custom_error_message) > 0:
            message = self._custom_error_message
            self._custom_error_message = ''

        lines = message.split('\n')
        linum = 0
        formatted_message = ''
        for line in lines:
            if linum == 0:
                formatted_message = 'Error: ' + line
            else:
                formatted_message += '\n       ' + line
            linum += 1

        sys.stderr.write(Fore.LIGHTRED_EX + '{}\n\n'.format(formatted_message) + Fore.RESET)
        # sys.stderr.write('{}\n\n'.format(formatted_message))
        self.print_help()
        sys.exit(1)
687898
def _error_check(err, prefix=""):
    """"""
    if err != 0:
        err_str = _snd.sf_error_number(err)
        raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
52498
def _get_error_message(self, model_class, method_name, action_method_name):
        
        if action_method_name:
            return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name, action_method_name)
        else:
            return "'{}' does not have '{}' defined.".format(model_class, method_name)
438050
function getError(errno, app) {
	let errObj = {
		errno: errno,
		message: errors[errno].replace('$app', app)
	};
	return errObj.message;
}