Wraps the given validator callable, replacing any error messages raised.
771561
def Msg(validator, message):
    
    @wraps(Msg)
    def built(value):
        try:
            return validator(value)
        except Error as e:
            e.message = message
            raise e
    return built
437316
function wrapError(spec, parsePayload) {
  return async function errorHandler(ctx, next) {
    try {
      await parsePayload(ctx, next);
    } catch (err) {
      captureError(ctx, 'type', err);
      if (spec.validate.continueOnError) {
        return await next();
      } else {
        return ctx.throw(err);
      }
    }
  };
}
1201888
def _wrap_callback_errors(callback, message):
    
    try:
        callback(message)
    except Exception:
        # Note: the likelihood of this failing is extremely low. This just adds
        # a message to a queue, so if this doesn't work the world is in an
        # unrecoverable state and this thread should just bail.
        _LOGGER.exception(
            "Top-level exception occurred in callback while processing a " "message"
        )
        message.nack()
62749
def wrap_rethink_errors(func_, *args, **kwargs):
    
    try:
        return func_(*args, **kwargs)
    except WRAP_RETHINK_ERRORS as reql_err:
        raise ValueError(str(reql_err))
438273
private void notifyOnValidationFailure(@NonNull final Validator<ValueType> validator) {
        for (ValidationListener<ValueType> listener : listeners) {
            listener.onValidationFailure(this, validator);
        }
    }
299889
def validate(func):
    
    call = PythonCall(func)

    @wraps(func)
    def decorator(*args, **kwargs):
        parameters = call.bind(args, kwargs)
        for arg_name, validator in func.__annotations__.items():
            if not validator(parameters[arg_name]):
                raise TypeError(
                    "Argument {!r} failed to validate".format(arg_name))
        return call.apply(args, kwargs)
    return decorator
116987
def run_validators(self, value):
        
        errors = []
        for validator in self.validators:
            if hasattr(validator, 'set_context'):
                validator.set_context(self)

            try:
                validator(value)
            except ValidationError as exc:
                # If the validation error contains a mapping of fields to
                # errors then simply raise it immediately rather than
                # attempting to accumulate a list of errors.
                if isinstance(exc.detail, dict):
                    raise
                errors.extend(exc.detail)
            except DjangoValidationError as exc:
                errors.extend(exc.messages)
        if errors:
            raise ValidationError(errors)
1063653
def _run_validators(self, value):
        
        if value in self.empty_values:
            return

        errors = []
        for validator in self.validators:
            try:
                validator(value)
            except exceptions.ValidationError as err:
                if isinstance(err.messages, dict):
                    errors.append(err.messages)
                else:
                    errors.extend(err.messages)

        if errors:
            raise exceptions.ValidationError(errors)
770696
def decorate_check_error(error_enum):
  """"""
  def decorator(func):
    @functools.wraps(func)
    def _check_error(*args, **kwargs):
      return check_error(func(*args, **kwargs), error_enum)
    return _check_error
  return decorator
292559
def validate_is_callable_or_none(option, value):
    """"""
    if value is None:
        return value
    if not callable(value):
        raise ValueError("%s must be a callable" % (option,))
    return value
999796
function(model, attr, value, computed) {
      // Reduces the array of validators to an error message by
      // applying all the validators and returning the first error
      // message, if any.
      return _.reduce(getValidators(model, attr), function(memo, validator){
        // Pass the format functions plus the default
        // validators as the context to the validator
        var ctx = _.extend({}, formatFunctions, defaultValidators),
            result = validator.fn.call(ctx, value, attr, validator.val, model, computed);

        if(result === false || memo === false) {
          return false;
        }
        if (result && !memo) {
          return _.result(validator, 'msg') || result;
        }
        return memo;
      }, '');
    }
71347
def play_all_validators(self, validators, value):
        
        successes = list()
        failures = OrderedDict()
        for validator in validators:
            name = get_callable_name(validator)
            try:
                res = validator(value)
                if result_is_success(res):
                    successes.append(name)
                else:
                    failures[validator] = res

            except Exception as exc:
                failures[validator] = exc

        return successes, failures
633326
def decorate_callable(self, callable_):
        """"""
        @wraps(callable_)
        def decorated(*args, **kwargs):
            # Extract timeout from request itself or use default for ioloop wrapper
            timeout = kwargs.get('timeout')
            return self.call_in_ioloop(callable_, args, kwargs, timeout)

        decorated.__doc__ = '\n\n'.join((
"""Wrapped async call. Will call in ioloop.

This call will block until the original callable has finished running on the ioloop, and
will pass on the return value. If the original callable returns a future, this call will
wait for the future to resolve and return the value or raise the exception that the future
resolves with.

Original Callable Docstring
---------------------------
""",
            textwrap.dedent(decorated.__doc__ or '')))

        return decorated
646213
def _wrap_class(request_handler, validator):
    
    METHODS = ['get', 'post', 'put', 'head', 'options', 'delete', 'patch']
    for name in METHODS:
        method = getattr(request_handler, name)
        setattr(request_handler, name, _auth_required(method, validator))

    return request_handler
1120867
def _exception_converter(callable: Callable) -> Callable:
    
    def wrapped(*args, **kwargs) -> Any:
        try:
            return callable(*args, **kwargs)
        except ConsulLockBaseError as e:
            raise e
        except ACLPermissionDenied as e:
            raise PermissionDeniedConsulError() from e
        except ConsulException as e:
            raise ConsulConnectionError() from e
    return wrapped
270774
def validate(**vkargs):
    
    def decorator(func):
        def wrapper(**kargs):
            for key, value in six.iteritems(vkargs):
                if key not in kargs:
                    abort(403, 'Missing parameter: %s' % key)
                try:
                    kargs[key] = value(kargs[key])
                except ValueError:
                    abort(403, 'Wrong parameter format for: %s' % key)
            return func(**kargs)
        return wrapper
    return decorator
88552
def wrap_formatter(formatter):
    
    if isinstance(formatter, ticker.Formatter):
        return formatter
    elif callable(formatter):
        args = [arg for arg in _getargspec(formatter).args
                if arg != 'self']
        wrapped = formatter
        if len(args) == 1:
            def wrapped(val, pos=None):
                return formatter(val)
        return ticker.FuncFormatter(wrapped)
    elif isinstance(formatter, basestring):
        if re.findall(r"\{(\w+)\}", formatter):
            return ticker.StrMethodFormatter(formatter)
        else:
            return ticker.FormatStrFormatter(formatter)