Wraps function fn in a try catch block that re-raises error_class.

    Args:
        fn (function): function to wrapped
        error_class (Exception): Error class to be re-raised

    Returns:
        (object): fn wrapped in a try catch.
505544
def error_wrapper(fn, error_class):  # type: (Callable or None, Exception) -> ...
    
    def wrapper(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except Exception as e:
            six.reraise(error_class, error_class(e), sys.exc_info()[2])

    return wrapper
1347817
def wrap(function, *args, **kwargs):
    ''''''
    try:
        req = function(*args, **kwargs)
        logger.debug('Got %s: %s', req.status_code, req.content)
        if req.status_code == 200:
            return req
        else:
            raise ClientException(req.reason, req.content)
    except ClientException:
        raise
    except Exception as exc:
        raise ClientException(exc)
92129
function makeFunctionWrapper(original, functionName) {
  //log("wrap fn: " + functionName);
  var f = original[functionName];
  return function() {
    //log("call: " + functionName);
    var result = f.apply(original, arguments);
    return result;
  };
}
52686
def memoize(fn):
    
    memoized_values = {}

    @wraps(fn)
    def wrapped_fn(*args, **kwargs):
        key = (args, tuple(sorted(kwargs.items())))
        try:
            return memoized_values[key]
        except KeyError:
            memoized_values[key] = fn(*args, **kwargs)
            return memoized_values[key]

    return wrapped_fn
1212181
def _wrapper(self, q, start):
        
        try:
            func_name = self.fnc.__name__
        except AttributeError:
            func_name = str(self.fnc)
        logger.debug("Running \"%s\" with parameters: \"%s\":\t%s/%s"
                     % (func_name, str(self.kwargs), round(time.time() - start), self.timeout))
        try:
            result = self.fnc(**self.kwargs)
            # let's log only first 50 characters of the response
            logger.debug("callback result = %s", str(result)[:50])
            q.put(result)
        except self.expected_exceptions as ex:
            logger.debug("expected exception was caught: %s", ex)
            q.put(False)
        except Exception as ex:
            logger.debug("adding exception %s to queue", ex)
            q.put(ex)
764523
def wrap_exception(func: Callable) -> Callable:
    """"""
    try:
        # only do the wrapping if pygatt is installed.
        # otherwise it's pointless anyway
        from pygatt.backends.bgapi.exceptions import BGAPIError
        from pygatt.exceptions import NotConnectedError
    except ImportError:
        return func

    def _func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except BGAPIError as exception:
            raise BluetoothBackendException() from exception
        except NotConnectedError as exception:
            raise BluetoothBackendException() from exception

    return _func_wrapper
1366521
def handle_api_exception(f):
    
    def wraps(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except SupersetSecurityException as e:
            logging.exception(e)
            return json_error_response(utils.error_msg_from_exception(e),
                                       status=e.status,
                                       stacktrace=traceback.format_exc(),
                                       link=e.link)
        except SupersetException as e:
            logging.exception(e)
            return json_error_response(utils.error_msg_from_exception(e),
                                       stacktrace=traceback.format_exc(),
                                       status=e.status)
        except Exception as e:
            logging.exception(e)
            return json_error_response(utils.error_msg_from_exception(e),
                                       stacktrace=traceback.format_exc())
    return functools.update_wrapper(wraps, f)
1273181
def reprovision_and_retry(func):
  
  @functools.wraps(func)
  def wrapper(*a, **kw):
    errback = kw.get('errback', None)
    if errback is None:
      def errback(e):
        raise e
    def errback_wrapper(e):
      if isinstance(e, UnknownAppID) and 'INITIAL' in OPTIONS:
        try:
          for initial in OPTIONS['INITIAL']:
            provision(*initial) # retry provisioning the initial setup
          func(*a, **kw) # and try the function once more
        except Exception, new_exc:
          errback(new_exc) # throwing the new exception
      else:
        errback(e) # not an instance of UnknownAppID - nothing we can do here
    kw['errback'] = errback_wrapper
    return func(*a, **kw)
  return wrapper
271211
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
          retry_log_level=logging.INFO,
          retry_log_message="Connection broken in '{f}' (error: '{e}'); "
                            "retrying with new connection.",
          max_failures=None, interval=0,
          max_failure_log_level=logging.ERROR,
          max_failure_log_message="Max retries reached for '{f}'. Aborting."):
    
    exc_classes = tuple(exc_classes)

    @wraps(f)
    def deco(*args, **kwargs):
        failures = 0
        while True:
            try:
                return f(*args, **kwargs)
            except exc_classes as e:
                if logger is not None:
                    logger.log(retry_log_level,
                               retry_log_message.format(f=f.func_name, e=e))
                gevent.sleep(interval)
                failures += 1
                if max_failures is not None \
                        and failures > max_failures:
                    if logger is not None:
                        logger.log(max_failure_log_level,
                                   max_failure_log_message.format(
                                       f=f.func_name, e=e))
                    raise
    return deco
300591
def _subclass_must_implement(self, fn):
        
        m = "Missing function implementation in {}: {}".format(type(self), fn)
        return NotImplementedError(m)
545291
def replace_exceptions(
    old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
    
    old_exceptions = tuple(old_to_new_exceptions.keys())

    def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
        @functools.wraps(to_wrap)
        # String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
        # Ignore so we don't have to import `Iterable`
        def wrapper(
            *args: Iterable[Any], **kwargs: Dict[str, Any]
        ) -> Callable[..., Any]:
            try:
                return to_wrap(*args, **kwargs)
            except old_exceptions as err:
                try:
                    raise old_to_new_exceptions[type(err)] from err
                except KeyError:
                    raise TypeError(
                        "could not look up new exception to use for %r" % err
                    ) from err

        return wrapper

    return decorator
700569
function wrap(fn) {
  // Error handling middleware
  if (fn.length === 4) {
    return async function wrappedErrorHandler(error, req, res, next) {
      next = _once(next);
      try {
        await fn(error, req, res, next);
        res.headersSent ? null : next();
      } catch(err) {
        res.headersSent ? null : next(err);
      }
    };
  }

  return async function wrappedMiddleware(req, res, next) {
    next = _once(next);
    try {
      await fn(req, res, next);
      res.headersSent ? null : next();
    } catch(err) {
      res.headersSent ? null : next(err);
    }
  };
}
19130
function once(fn) {
  var called, value;

  if (typeof fn !== 'function') {
    throw new Error('expected a function but got ' + fn);
  }

  return function wrap() {
    if (called) {
      return value;
    }
    called = true;
    value = fn.apply(this, arguments);
    fn = undefined;
    return value;
  };
}
713747
def raises(self, exception_type, function, *args, **kwargs):
        
        try:
            result = function(*args, **kwargs)
            self.log_error("{} did not throw exception {}".format(
                function.__name__,
                exception_type.__name__
            ), None)
            return result
        except Exception as e:
            if type(e) != exception_type:
                self.log_error("{} did raise {}: {}".format(
                    function.__name__,
                    type(e).__name__, e
                ), None)
177742
def raise_on_error(f):
    

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        retcode = GetLastError()
        if retcode and retcode != ERROR_IO_PENDING:
            err = WinError(code=retcode)
            windll.kernel32.SetLastError(0)  # clear error code so that we don't raise twice.
            raise err
        return result

    return wrapper
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
857872
def catch_exception(exception, message=None):
    
    def decorator(f):
        @click.pass_context
        def new_func(ctx, *args, **kwargs):
            try:
                return ctx.invoke(f, *args, **kwargs)
            except exception as e:
                message1 = message if message is not None else '{}'.format(e)
                click.echo(message1)
                ctx.exit(code=exit_codes.OTHER_FAILURE)
        return update_wrapper(new_func, f)
    return decorator