Exception mapping helper decorator. Takes the same arguments as the
        main decorator, plus `mapping`, which is a list of
        `(exception_class, status_line)` pairs.
185303
def map_exceptions(self, mapping, *args, **kwargs):
        
        @self.__call__(*args, **kwargs)
        def helper(e, status):
            return dict(exception=e), status

        def wrap(target):
            @wraps(target)
            def wrapper(*args, **kwargs):
                try:
                    return target(*args, **kwargs)
                except BaseException as e:
                    for klass, status in mapping:
                        if isinstance(e, klass):
                            return helper(e, status)
                    raise
            return wrapper
        return wrap
302331
def exception_translation(func):
    
    @wraps(func)
    def decorator(*arg, **kwargs):
        try:
            return func(*arg, **kwargs)
        except InvalidOperationException, e:
            return Response(status=status.HTTP_412_PRECONDITION_FAILED, data={'detail': e.message}, headers={'Content-Type': 'application/json'})
    return decorator
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)
766719
def on_exception_report_input(func_=None, force=False, keys=None):
    
    def _closure_onexceptreport(func):
        if not ONEX_REPORT_INPUT and not force:
            return func
        @ignores_exc_tb(outer_wrapper=False)
        #@wraps(func)
        def wrp_onexceptreport(*args, **kwargs):
            try:
                #import utool
                #if utool.DEBUG:
                #    print('[IN EXCPRPT] args=%r' % (args,))
                #    print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
                return func(*args, **kwargs)
            except Exception as ex:
                from utool import util_str
                print('ERROR occured! Reporting input to function')
                if keys is not None:
                    from utool import util_inspect
                    from utool import util_list
                    from utool import util_dict
                    argspec = util_inspect.get_func_argspec(func)
                    in_kwargs_flags = [key in kwargs for key in keys]
                    kwarg_keys = util_list.compress(keys, in_kwargs_flags)
                    kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
                    flags = util_list.not_list(in_kwargs_flags)
                    arg_keys = util_list.compress(keys, flags)
                    arg_idxs = [argspec.args.index(key) for key in arg_keys]
                    num_nodefault = len(argspec.args) - len(argspec.defaults)
                    default_vals = (([None] * (num_nodefault)) +
                                    list(argspec.defaults))
                    args_ = list(args) + default_vals[len(args) + 1:]
                    arg_vals = util_list.take(args_, arg_idxs)
                    requested_dict = dict(util_list.flatten(
                        [zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
                    print('input dict = ' + util_str.repr4(
                        util_dict.dict_subset(requested_dict, keys)))
                    # (print out specific keys only)
                    pass
                arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
                                      for arg in args])
                kwarg_strs = ', '.join([
                    util_str.truncate_str('%s=%r' % (key, val))
                    for key, val in six.iteritems(kwargs)])
                msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
                    meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
                msg += ' * len(args) = %r\n' % len(args)
                msg += ' * len(kwargs) = %r\n' % len(kwargs)
                util_dbg.printex(ex, msg, pad_stdout=True)
                raise
        wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func)
        return wrp_onexceptreport
    if func_ is None:
        return _closure_onexceptreport
    else:
        return _closure_onexceptreport(func_)
1012163
def translate_gitlab_exception(func):
    

    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except gitlab.GitlabError as e:
            status_to_exception = {
                401: UnauthorizedError,
                404: NotFoundError,
            }

            exc_class = status_to_exception.get(e.response_code, GitClientError)
            raise exc_class(str(e), status_code=e.response_code)

    return _wrapper
556531
def error_handler(f):
    

    @wraps(f)
    def error_handling_function(*args, **kwargs):
        @inject(error_config=ErrorConfiguration)
        def get_error_configuration(error_config):
            # type:(ErrorConfiguration)->ErrorConfiguration
            return error_config

        def should_skip_handling():
            use_flask_handler = get_error_configuration().use_flask_handler
            is_web_request = isinstance(JobContext.get_current_context(), WebJobContext)
            return use_flask_handler and is_web_request

        try:
            return f(*args, **kwargs)
        except Exception as ex:
            if should_skip_handling():
                raise

            for ep in _error_processors:
                ep.handle(ex)

            for eh in _error_handlers:
                if eh.can_handle(ex):
                    return eh.handle(ex)

            return _DEFAULT_ERROR_HANDLER.handle(ex)

    return error_handling_function
308892
def translate_exception(exc, kwargs):
    
    error = exc.response['Error']
    error.setdefault('Message', '')
    err_class = EXC.get(error['Code'], DynamoDBError)
    return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'],
                     exc_info=sys.exc_info(), args=pformat(kwargs), **error)
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
1037795
def exception_set(self, exception=None):
        
        if not exception:
            exception = sys.exc_info()
        self.exception = exception
        self.exception_raise = self._exception_raise
1033683
def prepare_raise(func):
    

    @functools.wraps(func)
    def decorator(type_, value=None, traceback=None):
        if value is not None and isinstance(type_, Exception):
            raise TypeError("instance exception may not have a separate value")

        if value is None:
            if isinstance(type_, Exception):
                error = type_
            else:
                error = type_()
        else:
            error = type_(value)
        func(error, value, traceback)

    return decorator
241583
def kw_map(**kws):
    
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for actual_name, kwarg_rename in kws.items():
                if kwarg_rename in kwargs:
                    kwargs[actual_name] = kwargs[kwarg_rename]
                    del kwargs[kwarg_rename]
            return func(*args, **kwargs)
        return wrapper
    return decorator
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)
1130301
def add_exception_handler(self, exception_handler):
        # type: (AbstractExceptionHandler) -> None
        
        if exception_handler is None:
            raise RuntimeConfigException(
                "Valid Exception Handler instance to be provided")

        if not isinstance(exception_handler, AbstractExceptionHandler):
            raise RuntimeConfigException(
                "Input should be an ExceptionHandler instance")

        self.exception_handlers.append(exception_handler)
237814
def _map_exception(e):
    """"""
    if isinstance(e, urllib3.exceptions.MaxRetryError):
        if not e.reason:
            return e
        e = e.reason
    message = e.args[0] if e.args else ''
    if isinstance(e, urllib3.exceptions.ResponseError):
        if 'too many redirects' in message:
            return httplib2.RedirectLimit(message)
    if isinstance(e, urllib3.exceptions.NewConnectionError):
        if ('Name or service not known' in message or
                'nodename nor servname provided, or not known' in message):
            return httplib2.ServerNotFoundError(
                'Unable to find hostname.')
        if 'Connection refused' in message:
            return socket.error((errno.ECONNREFUSED, 'Connection refused'))
    if isinstance(e, urllib3.exceptions.DecodeError):
        return httplib2.FailedToDecompressContent(
            'Content purported as compressed but not uncompressable.',
            httplib2.Response({'status': 500}), '')
    if isinstance(e, urllib3.exceptions.TimeoutError):
        return socket.timeout('timed out')
    if isinstance(e, urllib3.exceptions.SSLError):
        return ssl.SSLError(*e.args)

    return e
1198290
def exception(self, msg=None, *args, **kwargs):
        
        kwargs['exc_info'] = 1
        return self._log(logging.ERROR, msg, args, kwargs)
349487
def raise_api_exceptions(function, *args, **kwargs):
    
    try:
        return_value = function(*args, **kwargs)
    except errors.HTTPException as exc:
        if exc._raw.status_code != 400:  # pylint: disable=W0212
            raise  # Unhandled HTTPErrors
        try:  # Attempt to convert v1 errors into older format (for now)
            data = exc._raw.json()  # pylint: disable=W0212
            assert len(data) == 2
            return_value = {'errors': [(data['reason'],
                                        data['explanation'], '')]}
        except Exception:
            raise exc
    if isinstance(return_value, dict):
        if return_value.get('error') == 304:  # Not modified exception
            raise errors.NotModified(return_value)
        elif return_value.get('errors'):
            error_list = []
            for error_type, msg, value in return_value['errors']:
                if error_type in errors.ERROR_MAPPING:
                    if error_type == 'RATELIMIT':
                        args[0].evict(args[1])
                    error_class = errors.ERROR_MAPPING[error_type]
                else:
                    error_class = errors.APIException
                error_list.append(error_class(error_type, msg, value,
                                              return_value))
            if len(error_list) == 1:
                raise error_list[0]
            else:
                raise errors.ExceptionList(error_list)
    return return_value
530053
def error_map(func):
    
    @six.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except exceptions.RequestException as err:
            raise TVDBRequestException(
                err,
                response=getattr(err, 'response', None),
                request=getattr(err, 'request', None))
    return wrapper