Helper function to decode the raised Exception and give it a
        python Exception class
540217
def decodeRPCErrorMsg(e):
    
    found = re.search(
        (
            "(10 assert_exception: Assert Exception\n|"
            "3030000 tx_missing_posting_auth)"
            ".*: (.*)\n"
        ),
        str(e),
        flags=re.M,
    )
    if found:
        return found.group(2).strip()
    else:
        return str(e)
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
510917
def prepare_exception(obj, messages=None, response=None, verbs=None):
    
    # pylint:disable=too-many-branches
    verbs = set(verbs or [])
    known_options = ['method+url']
    if messages is None:
        messages = []
    if isinstance(messages, (text_type, str)):
        messages = [messages]
    assert isinstance(messages, list)
    assert not verbs.difference(known_options)

    data = None
    # a boolean from a failed response is False, though error messages in json should be decoded
    if response is not None and 'json' in response.headers.get('Content-Type', '') and response.text:
        data = json.loads(response.text)
        if data:
            data_0 = data[0]
            if 'errorCode' in data_0:
                subreq = ''
                if 'referenceId' in data_0:
                    subreq = " (in subrequest {!r})".format(data_0['referenceId'])
                messages = [data_0['errorCode'] + subreq] + messages
            if data_0.get('fields'):
                messages.append('FIELDS: {}'.format(data_0['fields']))
            if len(data) > 1:
                messages.append('MORE_ERRORS ({})'.format(len(data)))
    if 'method+url' in verbs:
        method = response.request.method
        url = response.request.url
        if len(url) > 100:
            url = url[:100] + '...'
        data_info = ''
        if (method in ('POST', 'PATCH') and
                (not response.request.body or 'json' not in response.request.headers['content-type'])):
            data_info = ' (without json request data)'
        messages.append('in {} "{}"{}'.format(method, url, data_info))
    separ = '\n    '
    if not PY3:
        messages = [x if isinstance(x, str) else x.encode('utf-8') for x in messages]
    messages = [x.replace('\n', separ) for x in messages]
    message = separ.join(messages)
    if obj:
        obj.data = data
        obj.response = response
        obj.verbs = verbs
    return message
628359
def capture_exception(fn):
    """"""
    def wrapped(*args):
        try:
            return fn(*args)
        except Exception as e:
            return e
    return wrapped
452040
def error_response(self, exception):
        # type: (Exception) -> Tuple[Callback, Error]
        """"""
        response = Error(id=self.id, message=exception)
        log.exception("Exception raised for request %s", self)
        return self.callback, response
779285
def raises_regex(self, expected_exception, expected_regexp):
        
        return unittest_case.assertRaisesRegexp(expected_exception, expected_regexp, self._orig_subject,
                                                *self._args, **self._kwargs)
1235639
def update_exc(base_exceptions, *addition_dicts):
    
    exc = dict(base_exceptions)
    for additions in addition_dicts:
        for orth, token_attrs in additions.items():
            if not all(isinstance(attr[ORTH], unicode_) for attr in token_attrs):
                raise ValueError(Errors.E055.format(key=orth, orths=token_attrs))
            described_orth = "".join(attr[ORTH] for attr in token_attrs)
            if orth != described_orth:
                raise ValueError(Errors.E056.format(key=orth, orths=described_orth))
        exc.update(additions)
    exc = expand_exc(exc, "'", "’")
    return exc
149536
def exception_handler(self, pdb):
        '''
        

        '''

        # Grab the exception
        exctype, value, tb = sys.exc_info()

        # Log the error and create a .err file
        errfile = os.path.join(self.dir, self.name + '.err')
        with open(errfile, 'w') as f:
            for line in traceback.format_exception_only(exctype, value):
                ln = line.replace('\n', '')
                log.error(ln)
                print(ln, file=f)
            for line in traceback.format_tb(tb):
                ln = line.replace('\n', '')
                log.error(ln)
                print(ln, file=f)

        # Re-raise?
        if pdb:
            raise
619768
def ExceptionHook(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
110099
def get_exceptions(self):
          # noqa

        buff = self.get_attribute("Exceptions")
        if buff is None:
            return ()

        with unpack(buff) as up:
            return tuple(self.deref_const(e[0]) for e
                         in up.unpack_struct_array(_H))
525989
def _raise_error(self, status_code, raw_data):
        
        error_message = raw_data
        additional_info = None
        try:
            if raw_data:
                additional_info = json.loads(raw_data)
                error_message = additional_info.get('error', error_message)
                if isinstance(error_message, dict) and 'type' in error_message:
                    error_message = error_message['type']
        except (ValueError, TypeError) as err:
            logger.warning('Undecodable raw error response from server: %s', err)

        raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
186207
def api_exception(http_code):
    
    def wrapper(*args):
        code = args[0]
        ErrorMapping.mapping[http_code] = code
        return code
    return wrapper
800894
def exception(function):
    
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except Exception as e:
            # print 
            err = "There was an exception in %s():"%(function.__name__)
            print(("%s \n %s \n%s"%(err,e,sys.exc_info())))
            return -1
 
    return wrapper
1249818
def make_exception_message(exc):
    
    if str(exc):
        return '%s: %s\n' % (exc.__class__.__name__, exc)
    else:
        return '%s\n' % (exc.__class__.__name__)
230445
def raise_error(name=None, args=None, message=''):
    '''
    
    '''
    name = name or 'Exception'
    if hasattr(salt.exceptions, name):
        ex = getattr(salt.exceptions, name)
    elif hasattr(exceptions, name):
        ex = getattr(exceptions, name)
    else:
        name = 'SaltException'
        ex = getattr(salt.exceptions, name)
    if args is not None:
        raise ex(*args)
    else:
        raise ex(message)
447169
def getExceptionClass(errorCode):
    
    classMap = {}
    for name, class_ in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(class_) and issubclass(class_, BaseServerException):
            classMap[class_.getErrorCode()] = class_
    return classMap[errorCode]
1207620
def unhandled(exception, opt):
    
    exmod = type(exception).__module__
    name = "%s.%s" % (exmod, type(exception).__name__)
    # this is a Vault error
    if exmod == 'aomi.exceptions' or exmod == 'cryptorito':
        # This may be set for Validation or similar errors
        if hasattr(exception, 'source'):
            output(exception.message, opt, extra=exception.source)
        else:
            output(exception.message, opt)

    else:
        output("Unexpected error: %s" % name, opt)

    sys.exit(1)