TODO[ES5]: Improve error message using JSON.stringify eventually.
352235
function range(begin, end) {
  return test(function(ch) {
    return begin <= ch && ch <= end;
  }).desc(begin + "-" + end);
}
555533
function formatRequestErrors(request, errors) {
  const CONTEXT_BEFORE = 20;
  const CONTEXT_LENGTH = 60;

  const queryLines = request.getQueryString().split('\n');
  return errors.map(({locations = [], message}, ii) => {
    const prefix = (ii + 1) + '. ';
    const indent = ' '.repeat(prefix.length);
    return (
      prefix + message + '\n' +
      locations.map(({column, line}) => {
        const queryLine = queryLines[line - 1];
        const offset = Math.min(column - 1, CONTEXT_BEFORE);
        return [
          queryLine.substr(column - 1 - offset, CONTEXT_LENGTH),
          ' '.repeat(offset) + '^^^',
        ].map(messageLine => indent + messageLine).join('\n');
      }).join('\n')
    );
  }).join('\n');
}
1004322
def error(code, message, template):
    """"""
    if json_requested():
        return json_error(code, message)
    else:
        return render_template(template, message=message), code
216159
function(error) {
  if (error instanceof Error) return error;

  var msg = error.err || error.errmsg || error.errMessage || error;
  var e = MongoError.create({ message: msg, driver: true });

  // Get all object keys
  var keys = typeof error === 'object' ? Object.keys(error) : [];

  for (var i = 0; i < keys.length; i++) {
    try {
      e[keys[i]] = error[keys[i]];
    } catch (err) {
      // continue
    }
  }

  return e;
}
980912
function fixNonStringValue(value, skipError) {
  if (typeof value !== 'string') {
    return value;
  }

  if (value === '') {
    return undefined;
  }

  var lcValue = value.toLowerCase();

  if (lcValue === 'true') {
    return true;
  }
  if (lcValue === 'false') {
    return false;
  }

  try {
    return JSON.parse(value);
  } catch (e) {
    //TODO: report warning
    if (skipError === true) {
      return undefined;
    }

    throw new SwaggerConverterError('incorect property value: ' + e.message);
  }
}
916184
private static function catchError()
    {
        switch (json_last_error()) {
            case JSON_ERROR_NONE:
                self::$error = false;
                break;
            case JSON_ERROR_DEPTH:
                self::$error = 'Maximum stack depth exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                self::$error = 'Underflow or the modes mismatch';
                break;
            case JSON_ERROR_CTRL_CHAR:
                self::$error = 'Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                self::$error = 'Syntax error, malformed JSON';
                break;
            case JSON_ERROR_UTF8:
                self::$error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
            default:
                self::$error = 'Unknown error';
                break;
        }
    }
834205
function sendError(msg, file, line, col, err) {
        var errString = 'JSON not found';
        if (window.JSON) {
            errString = JSON.stringify(err);
        }

        if (typeof(msg) === 'object') {
            file      = msg.filename;
            line      = msg.lineno;
            col       = msg.colno;
            errString = msg.error.stack;
            msg       = msg.message;
        }

        new Image().src = pathServerAPI + 'jserrors?msg=' + encodeURIComponent(msg) + '&file=' + encodeURIComponent(file) + '&line=' + encodeURIComponent(line) + '&col=' + encodeURIComponent(col) + '&err=' + encodeURIComponent(errString);
    }
1123299
private void sendErrorJSON(HttpServletResponse response, int statusCode, String errorCode, String errorDescription) {
        final String error = "error";
        final String error_description = "error_description";
        try {
            if (errorCode != null) {
                response.setStatus(statusCode);
                response.setHeader(ClientConstants.REQ_CONTENT_TYPE_NAME,
                        "application/json;charset=UTF-8");

                JSONObject responseJSON = new JSONObject();
                responseJSON.put(error, errorCode);
                if (errorDescription != null) {
                    responseJSON.put(error_description, errorDescription);
                }
                PrintWriter pw;
                pw = response.getWriter();
                pw.write(responseJSON.toString());
                pw.flush();
            } else {
                response.sendError(statusCode);
            }
        } catch (IOException e) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Internal error sending error message", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException ioe) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "yet another internal error, give up", ioe);
            }
        }

    }
738676
function detectCustomErrorMessage(key) {
            if (typeof properties[key] === 'object' && properties[key].errorMessage && properties[key].value) {
                return properties[key];
            }
            else  if (_.isArray(properties[key])) {
                return {
                    value: properties[key][0],
                    errorMessage: properties[key][1]
                };
            }
            else {
                return {
                    value: properties[key],
                    errorMessage: undefined
                };
            }
        }
480761
function formatError(error) {
        function localize(key) {
            if (Strings[key]) {
                return Strings[key];
            }
            console.log("Unknown installation error", key);
            return Strings.UNKNOWN_ERROR;
        }

        if (Array.isArray(error)) {
            error[0] = localize(error[0]);
            return StringUtils.format.apply(window, error);
        } else {
            return localize(error);
        }
    }
675952
function(err) {
            var msg = angular.isString(err) ? err : (err.message || err.data || err.statusText);
            $log.warn(msg);
            reject(err);
          }
1264078
function stringify (value, replacer, spaces, escape) {
  // v8 checks arguments.length for optimizing simple call
  // https://bugs.chromium.org/p/v8/issues/detail?id=4730
  var json = replacer || spaces
    ? JSON.stringify(value, replacer, spaces)
    : JSON.stringify(value);

  if (escape) {
    json = json.replace(/[<>&]/g, function (c) {
      switch (c.charCodeAt(0)) {
        case 0x3c:
          return '\\u003c'
        case 0x3e:
          return '\\u003e'
        case 0x26:
          return '\\u0026'
        default:
          return c
      }
    })
  }

  return json
}
396775
function(flat) {
    var errors = flat ? [this.errors[0]] : this.errors;
    return this.key + ': ' +
      _.map(errors, 'message').join(', ');
  }
766881
function lexError(message, input, index) {
	let lexMessage = message + "\n\n";

	// Show input characters surrounding the source of the error.
	for (
		let i = Math.max(0, index - 16);
		i < Math.min(index + 16, input.length);
		i++
	) {
		lexMessage += input[i];
	}

	error(lexMessage);
}
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
1242665
function errorToString(err) {
   if (isUndefined(err)) {
      return undefined;
   } else if (err.toString().length > maxStatusDetailLength) {
      return err.toString().substring(0, maxStatusDetailLength - 3) + '...';
   } else {
      return err.toString();
   }
}
285244
function errorSerializer (err) {
  if (!err || !err.stack) return err
  const obj = {
    message: err.message,
    name: err.name,
    code: err.code,
    stack: getErrorStack(err)
  }
  return obj
}