Call `func(self)`, catching any exception that might occur, logging it,
        and force-disconnecting the related `stream`.
540442
def _call(self, stream, func):
        
        try:
            func(self)
        except Exception:
            LOG.exception('%r crashed', stream)
            stream.on_disconnect(self)
912503
def retry(func):
    
    def retried_func(*args, **kwargs):
        max_tries = 3
        tries = 0
        while True:
            try:
                resp = func(*args, **kwargs)

            except requests.exceptions.ConnectionError as exc:
                exc.msg = "Connection error for session; exiting"
                raise exc

            except requests.exceptions.HTTPError as exc:
                exc.msg = "HTTP error for session; exiting"
                raise exc

            if resp.status_code != 200 and tries < max_tries:
                logger.warning("retrying request; current status code: {}"
                               .format(resp.status_code))
                tries += 1
                # mini exponential backoff here.
                time.sleep(tries ** 2)
                continue

            break

        if resp.status_code != 200:
            error_message = resp.json()["error"]["message"]
            logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
            logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
            raise requests.exceptions.HTTPError

        return resp

    return retried_func
147360
def on_disconnect(self, code, stream_name, reason):
        """"""
        logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
        return True
1356875
def threaded(system, func, *args, **kwargs):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            if system.raven_client:
                system.raven_client.captureException()
            logger.exception('Exception occurred in thread: %s', e)
            return False

    return lambda: wrapper(*args, **kwargs)
1152705
def handle_exception(logger, **kw_decorator):
    

    def decorator(query_func):
        @functools.wraps(query_func)
        def wrapper(*args, **kwargs):
            try:
                return query_func(*args, **kwargs)
            except Exception as e:
                logger.info('Exception in function {0} -- {1}'.format(query_func.__name__, e))
                if valid_dict(kw_decorator, ['subject', 'sender', 'username', 'password', 'host', 'receiver']):
                    logger.info('Now is sending the email with exception message')
                    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    msg = t + ' ' + 'Exception in function {0} -- {1}'.format(query_func.__name__, e)
                    _send(subject=kw_decorator['subject'],
                          text=msg,
                          sender=kw_decorator['sender'],
                          username=kw_decorator['username'],
                          password=kw_decorator['password'],
                          host=kw_decorator['host'],
                          receiver=kw_decorator['receiver'])

                    logger.info('Email is sent')

        return wrapper

    return decorator
1332706
async def cancel(self):
        
        if self._cancel_done:
            raise ProtocolError('Stream was already cancelled')

        with self._wrapper:
            await self._stream.reset()  # TODO: specify error code
            self._cancel_done = True
422281
def threadpooled(
    func: None = None,
    *,
    loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None,
    loop_getter_need_context: bool = False,
) -> ThreadPooled:
    """"""
1196721
function catchError (stream) {
  return {
    source: pull(
      stream.source,
      pullCatch((err) => {
        if (err.message === 'Channel destroyed') {
          return
        }
        return false
      })
    ),
    sink: stream.sink
  }
}
1200071
def start(self):
        
        err = _pa.Pa_StartStream(self._stream)
        if err == _pa.paStreamIsNotStopped:
            return
        self._handle_error(err)
1083137
def process_exception(self, request, exception):
        
        if hasattr(threadlocal, 'actionslog'):
            pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])

        return None
608627
def retry(func, exception_type, quit_event):
    
    while True:
        if quit_event.is_set():
            raise StopIteration
        try:
            return func()
        except exception_type:
            pass
335459
def async_call(func, *args, callback=None):
    '''
    '''
    def do_call():
        result = None
        error = None

        try:
            result = func(*args)
        except Exception:
            error = traceback.format_exc()
            logger.error(error)
        if callback:
            GLib.idle_add(callback, result, error)

    thread = threading.Thread(target=do_call)
    thread.daemon = True
    thread.start()
1295512
def onExit(self):
        
        def try_call(fn):
            try:
                fn()
            except (pika.exceptions.ChannelClosed, AttributeError,
                    pika.exceptions.ConnectionClosed):
                return

        if hasattr(self, "channel"):
            try_call(self.channel.cancel)
            try_call(self.channel.close)
            try_call(self.connection.close)
744871
def check_for_error(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            response = func(*args, **kwargs)
            status_code = response.status_code
            if status_code in range(200, 204):
                return response
            if status_code == 204:
                return
            data = response.json()
            e = {
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
                405: MethodNotAllowed,
                408: RequestTimeout,
                409: Conflict,
                429: TooManyRequests,
                500: ServerError,
                503: ServiceUnavailable,
            }.get(status_code, SbgError)()
            if 'message' in data:
                e.message = data['message']
            if 'code' in data:
                e.code = data['code']
            if 'status' in data:
                e.status = data['status']
            if 'more_info' in data:
                e.more_info = data['more_info']
            raise e
        except requests.RequestException as e:
            raise SbgError(message=six.text_type(e))
        except JSONDecodeError:
            message = (
                'Service might be unavailable. Can also occur by providing '
                'too many query parameters.'
            )
            raise_from(
                ServiceUnavailable(message=six.text_type(message)), None
            )
        except ValueError as e:
            raise SbgError(message=six.text_type(e))

    return wrapper
862365
def no_exception(on_exception, logger=None):
    

    def decorator(function):
        def wrapper(*args, **kwargs):
            try:
                result = function(*args, **kwargs)
            except Exception, e:
                if hasattr(logger, 'exception'):
                    logger.exception(e)
                else:
                    print traceback.format_exc()
                result = on_exception
            return result

        return wrapper

    return decorator
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
419830
def catch_exceptions(orig_func):
    """"""

    @functools.wraps(orig_func)
    def catch_exceptions_wrapper(self, *args, **kwargs):
        try:
            return orig_func(self, *args, **kwargs)
        except arvados.errors.ApiError as e:
            logging.exception("Failure")
            return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
        except subprocess.CalledProcessError as e:
            return {"msg": str(e), "status_code": 500}, 500
        except MissingAuthorization:
            return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
        except ValueError as e:
            return {"msg": str(e), "status_code": 400}, 400
        except Exception as e:
            return {"msg": str(e), "status_code": 500}, 500

    return catch_exceptions_wrapper