Decorator to drop into the debugger if a function throws an exception.
482417
def _catch(f, exception_type):
  """"""
  if not (inspect.isclass(exception_type)
          and issubclass(exception_type, Exception)):
    exception_type = Exception

  @functools.wraps(f)
  def wrap(*args, **kw):
    try:
      return f(*args, **kw)
    except exception_type as e:  # pylint: disable=broad-except
      qj(e, 'Caught an exception in %s' % f, d=1, _depth=2)
  return wrap
1228701
def debug_callback(event, *args, **kwds):
    '''
    '''
    l = ['event %s' % (event.type,)]
    if args:
        l.extend(map(str, args))
    if kwds:
        l.extend(sorted('%s=%s' % t for t in kwds.items()))
    print('Debug callback (%s)' % ', '.join(l))
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
90253
def _exception_free_callback(self, callback, *args, **kwargs):
        
        try:
            return callback(*args, **kwargs)
        except Exception:
            self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
            return None
238418
def exception_handler(self, callback):
        
        path = '.'.join([callback.__module__, callback.__name__])
        self._exception_handlers.append(path)
        return callback
1287659
def exception_wrapper(f):
    """"""
    @wraps(f)
    def wrapper(*args, **kwds):
        try:
            return f(*args, **kwds)
        except dbus.exceptions.DBusException as err:
            _args = err.args
            raise PyMPRISException(*_args)
    return wrapper
427300
def exception_handler(exctype, value, traceback):
    
    if exctype == KeyboardInterrupt:
        pypro.console.out('')  # Adds a new line after Ctrl+C character
        pypro.console.err('Canceled')
    elif exctype == PyproException:
        pypro.console.err('[Error] ', value.message)
        exit()
    else:
        sys.__excepthook__(exctype, value, traceback)
719403
def wrapply(func, *args, **kwargs):
    ''
    val = args[0]
    if val is None:
        return TypedWrapper(func, None)
    elif isinstance(val, TypedExceptionWrapper):
        tew = copy(val)
        tew.forwarded = True
        return tew
    elif isinstance(val, TypedWrapper):
        return val
    elif isinstance(val, Exception):
        return TypedWrapper(func, *args)

    try:
        return func(*args, **kwargs)
    except Exception as e:
        e.stacktrace = stacktrace()
        return TypedExceptionWrapper(func, *args, exception=e)
1316452
def log_exception(func, handler, args, kwargs):
    
    # safe-guard: expected arguments -> log_exception(self, typ, value, tb)
    value = args[1] if len(args) == 3 else None
    if value is None:
        return func(*args, **kwargs)

    tracing = handler.settings.get('opentracing_tracing')
    if not isinstance(value, HTTPError) or 500 <= value.status_code <= 599:
        tracing._finish_tracing(handler, error=value)

    return func(*args, **kwargs)
378615
def log_errors(function):
    """"""

    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except BaseException as e:
            handle_exception(None, e, "Exception in function %s",
                             reflect.canonical_name(function))
            raise

    return wrapper
792137
def email_uncaught_exception(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except:
            logger = logging.getLogger('dbbackup')
            exc_type, exc_value, tb = sys.exc_info()
            tb_str = ''.join(traceback.format_tb(tb))
            msg = '%s: %s\n%s' % (exc_type.__name__, exc_value, tb_str)
            logger.error(msg)
            raise
        finally:
            connection.close()
    return wrapper
1024940
def base_exception_handler(*args):
    

    header, frames, trcback = format_report(*extract_exception(*args))

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    map(lambda x: LOGGER.error("!> {0}".format(x)), header)

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    map(lambda x: LOGGER.error("!> {0}".format(x)), frames)

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    sys.stderr.write("\n".join(trcback))

    return True
920084
def _connection_error_wrapper(func, *args, **kwargs):
    

    counter = 0
    while counter < 5:
        try:
            result = func(*args, **kwargs)
            return result
        except Exception as ex:
            time.sleep(5)
            counter += 1
            logging.warning(str(ex))
1110781
def wrap_exception(func: Callable) -> Callable:
    """"""

    def _func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except IOError as exception:
            raise BluetoothBackendException() from exception
    return _func_wrapper
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)
337674
def clean_fail(func):
    '''
    
    '''
    def func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except botocore.exceptions.ClientError as e:
            print(str(e), file=sys.stderr)
            sys.exit(1)
    return func_wrapper
749867
def throws_errors(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)

        # if no status code is provided, assume 400
        if isinstance(response, BugZooException):
            err_jsn = flask.jsonify(response.to_dict())
            return err_jsn, 400

        if isinstance(response, tuple) \
           and isinstance(response[0], BugZooException):
            err = response[0] # type: BugZooException
            err_jsn = flask.jsonify(err.to_dict())
            return (err_jsn, *response[1:])

        return response

    return wrapper