Decorator to wrap pygatt exceptions into BluetoothBackendException.
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
1277688
def exception_handler(exceptionObj):
    """"""
    try:
        if isinstance(exceptionObj, Exception) and hasattr(exceptionObj, 'args'):
            if not (hasattr(exceptionObj, 'message' or hasattr(exceptionObj, 'msg'))):
                if len(exceptionObj.args) >= 1:
                    if type(exceptionObj.args[0]) == type(b''):
                        ob = json.loads(exceptionObj.args[0].decode('utf-8'))
                        if type(ob) == type({}) and ob['message']:
                            return ob['message']
                    else:

                        try:
                            if type(exceptionObj.args[0]) == type('') and exceptionObj.args[0][0] == 'b':
                                ob = json.loads(exceptionObj.args[0][2:-1])
                            else:
                                ob = json.loads(exceptionObj.args[0])
                            if type(ob) == type({}) and ob['message']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['message']
                            elif type(ob) == type({}) and ob['msg']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['msg']
                            return str(json.loads(exceptionObj.args[0]))
                        except Exception as e:
                            return str(exceptionObj.args[0])
            elif hasattr(exceptionObj, 'msg'):
                return exceptionObj.msg
            elif hasattr(exceptionObj, 'message'):
                return exceptionObj.message
        elif type(exceptionObj) == type(''):
            try:
                ob = json.loads(exceptionObj)
                if type(ob) == type({}):
                    if ob['message']:
                        return ob['message']
                    elif ob['msg']:
                        return ob['msg']
                    else:
                        return ob
            except Exception as e:
                return exceptionObj

    except Exception as e:
        return e
452025
def wrap_sync(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.Future()
        def green():
            try:
                fut.set_result(func(*args, **kwargs))
            except BaseException as e:
                fut.set_exception(e)
        greenlet.greenlet(green).switch()
        return fut
    return wrapped
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
568931
def display_error(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except wandb.Error as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(
                exc_type, exc_value, exc_traceback)
            logger.error(''.join(lines))
            click_exc = ClickWandbException(e)
            click_exc.orig_type = exc_type
            six.reraise(ClickWandbException, click_exc, sys.exc_info()[2])
    return wrapper
1314225
def ignore_exceptions(f):
    """"""
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except:
            logging.exception("Ignoring exception in %r", f)
    return wrapped
792350
def _from_exception(cls, pe):
        
        return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
110790
def log_exception(self, exception_info: Tuple[type, BaseException, TracebackType]) -> None:
        
        if has_request_context():
            request_ = _request_ctx_stack.top.request
            self.logger.error(
                f"Exception on request {request_.method} {request_.path}",
                exc_info=exception_info,
            )
        if has_websocket_context():
            websocket_ = _websocket_ctx_stack.top.websocket
            self.logger.error(
                f"Exception on websocket {websocket_.path}",
                exc_info=exception_info,
            )
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)
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)
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
362090
def wrap_errorhandler(app):
        
        try:
            existing_handler = app.error_handler_spec[None][404][NotFound]
        except (KeyError, TypeError):
            existing_handler = None

        if existing_handler:
            app.error_handler_spec[None][404][NotFound] = \
                lambda error: handle_not_found(error, wrapped=existing_handler)
        else:
            app.error_handler_spec.setdefault(None, {}).setdefault(404, {})
            app.error_handler_spec[None][404][NotFound] = handle_not_found
588463
def generate_crash_handler_decorator(error_decorator=None):
    """"""

    def crash_handler(f):
        """Return a decorator that reports failed api calls via the error_reporter,
        for use on every server endpoint"""

        @wraps(f)
        def wrapper(*args, **kwargs):
            """Generate a report of this api call, and if the call failed or was too slow,
            forward this report via the error_reporter"""

            data = {}
            t0 = timenow()
            exception_string = ''

            # Call endpoint and log execution time
            try:
                res = f(*args, **kwargs)
            except Exception as e:
                # An unhandled exception occured!
                exception_string = str(e)
                exc_type, exc_value, exc_traceback = sys.exc_info()
                trace = traceback.format_exception(exc_type, exc_value, exc_traceback, 30)
                data['trace'] = trace

                # If it is a PyMacaronException, just call its http_reply()
                if hasattr(e, 'http_reply'):
                    res = e.http_reply()
                else:
                    # Otherwise, forge a Response
                    e = UnhandledServerError(exception_string)
                    log.error("UNHANDLED EXCEPTION: %s" % '\n'.join(trace))
                    res = e.http_reply()

            t1 = timenow()

            # Is the response an Error instance?
            response_type = type(res).__name__
            status_code = 200
            is_an_error = 0
            error = ''
            error_description = ''
            error_user_message = ''

            error_id = ''

            if isinstance(res, Response):
                # Got a flask.Response object
                res_data = None

                status_code = str(res.status_code)

                if str(status_code) == '200':

                    # It could be any valid json response, but it could also be an Error model
                    # that pymacaron_core handled as a status 200 because it does not know of
                    # pymacaron Errors
                    if res.content_type == 'application/json':
                        s = str(res.data)
                        if '"error":' in s and '"error_description":' in s and '"status":' in s:
                            # This looks like an error, let's decode it
                            res_data = res.get_data()
                else:
                    # Assuming it is a PyMacaronException.http_reply()
                    res_data = res.get_data()

                if res_data:
                    if type(res_data) is bytes:
                        res_data = res_data.decode("utf-8")

                    is_json = True
                    try:
                        j = json.loads(res_data)
                    except ValueError as e:
                        # This was a plain html response. Fake an error
                        is_json = False
                        j = {'error': res_data, 'status': status_code}

                    # Make sure that the response gets the same status as the PyMacaron Error it contained
                    status_code = j['status']
                    res.status_code = int(status_code)

                    # Patch Response to contain a unique id
                    if is_json:
                        if 'error_id' not in j:
                            # If the error is forwarded by multiple micro-services, we
                            # want the error_id to be set only on the original error
                            error_id = str(uuid.uuid4())
                            j['error_id'] = error_id
                            res.set_data(json.dumps(j))

                        if error_decorator:
                            # Apply error_decorator, if any defined
                            res.set_data(json.dumps(error_decorator(j)))

                    # And extract data from this error
                    error = j.get('error', 'NO_ERROR_IN_JSON')
                    error_description = j.get('error_description', res_data)
                    if error_description == '':
                        error_description = res_data

                    if not exception_string:
                        exception_string = error_description

                    error_user_message = j.get('user_message', '')
                    is_an_error = 1


            request_args = []
            if len(args):
                request_args.append(args)
            if kwargs:
                request_args.append(kwargs)

            data.update({
                # Set only on the original error, not on forwarded ones, not on
                # success responses
                'error_id': error_id,

                # Call results
                'time': {
                    'start': t0.isoformat(),
                    'end': t1.isoformat(),
                    'microsecs': (t1.timestamp() - t0.timestamp()) * 1000000,
                },

                # Response details
                'response': {
                    'type': response_type,
                    'status': str(status_code),
                    'is_error': is_an_error,
                    'error_code': error,
                    'error_description': error_description,
                    'user_message': error_user_message,
                },

                # Request details
                'request': {
                    'params': pformat(request_args),
                },
            })

            populate_error_report(data)

            # inspect may raise a UnicodeDecodeError...
            fname = function_name(f)

            #
            # Should we report this call?
            #

            # If it is an internal errors, report it
            if data['response']['status'] and int(data['response']['status']) >= 500:
                report_error(
                    title="%s(): %s" % (fname, exception_string),
                    data=data,
                    is_fatal=True
                )

            log.info("")
            log.info(" <= Done!")
            log.info("")

            return res

        return wrapper

    return crash_handler
87528
def threw(cls, spy, error_type=None):
        
        cls.__is_spy(spy)
        if not (spy.threw(error_type)):
            raise cls.failException(cls.message)
926585
def handle_backend_error(self, exception):
        
        idp = self._load_idp_dynamic_entity_id(exception.state)
        return self._handle_backend_error(exception, idp)
976789
def normalize_exceptions(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        message = "Whoa, you found a bug."
        try:
            return func(*args, **kwargs)
        except requests.HTTPError as err:
            raise CommError(err.response, err)
        except RetryError as err:
            if "response" in dir(err.last_exception) and err.last_exception.response is not None:
                try:
                    message = err.last_exception.response.json().get(
                        'errors', [{'message': message}])[0]['message']
                except ValueError:
                    message = err.last_exception.response.text
            else:
                message = err.last_exception

            six.reraise(CommError, CommError(
                message, err.last_exception), sys.exc_info()[2])
        except Exception as err:
            # gql raises server errors with dict's as strings...
            if len(err.args) > 0:
                payload = err.args[0]
            else:
                payload = err
            if str(payload).startswith("{"):
                message = ast.literal_eval(str(payload))["message"]
            else:
                message = str(err)
            if wandb.env.is_debug():
                six.reraise(*sys.exc_info())
            else:
                six.reraise(CommError, CommError(
                    message, err), sys.exc_info()[2])
    return wrapper
1006155
def wrap_exception(func: Callable) -> Callable:
    """"""
    try:
        # only do the wrapping if bluepy is installed.
        # otherwise it's pointless anyway
        from bluepy.btle import BTLEException
    except ImportError:
        return func

    def _func_wrapper(*args, **kwargs):
        error_count = 0
        last_error = None
        while error_count < RETRY_LIMIT:
            try:
                return func(*args, **kwargs)
            except BTLEException as exception:
                error_count += 1
                last_error = exception
                time.sleep(RETRY_DELAY)
                _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT)
        raise BluetoothBackendException() from last_error

    return _func_wrapper