Wrapper for repr() that catches exceptions.
553494
def safe_repr(source, max_length=0):
    """"""
    try:
        return ellipsis(repr(source), max_length)
    except Exception as e:
        return ellipsis("<n/a: repr(...) raised %s>" % e, max_length)
645008
def catch(checker, *a, **kw):
    
    try:
        return checker(*a, **kw)
    except DataError as error:
        return error
202688
def raise_exception(self, node, exc=None, msg='', expr=None,
                        lineno=None):
        """"""
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg
        err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
        self._interrupt = ast.Break()
        self.error.append(err)
        if self.error_msg is None:
            self.error_msg = "at expr='%s'" % (self.expr)
        elif len(msg) > 0:
            self.error_msg = msg
        if exc is None:
            try:
                exc = self.error[0].exc
            except:
                exc = RuntimeError
        raise exc(self.error_msg)
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
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
867664
def handle_exception(error):
    """"""
    try:
        if _get_acceptable_response_type() == JSON:
            response = jsonify(error.to_dict())
            response.status_code = error.code
            return response
        else:
            return error.abort()
    except InvalidAPIUsage:
        # In addition to the original exception, we don't support the content
        # type in the request's 'Accept' header, which is a more important
        # error, so return that instead of what was originally raised.
        response = jsonify(error.to_dict())
        response.status_code = 415
        return response
330212
def map_boto_exceptions(key=None, exc_pass=()):
    """"""
    from boto.exception import BotoClientError, BotoServerError, \
        StorageResponseError
    try:
        yield
    except StorageResponseError as e:
        if e.code == 'NoSuchKey':
            raise KeyError(key)
        raise IOError(str(e))
    except (BotoClientError, BotoServerError) as e:
        if e.__class__.__name__ not in exc_pass:
            raise IOError(str(e))
191630
def r_to_s(func):
    """"""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """"""

        class ReprToStr(str):
            """Replaces a class __repr__ with it's string representation"""
            def __repr__(self):
                return str(self)
        return ReprToStr(func(*args, **kwargs))
    return wrapper
98657
def repr_assist(obj, remap=None):
    
    if not remap:
        remap = {}
    data = []
    for arg in inspect.getargspec(getattr(obj.__class__, '__init__'))[0]:
        if arg == 'self':
            continue
        elif arg in remap:
            value = remap[arg]
        else:
            try:
                value = getattr(obj, arg)
            except AttributeError:
                value = getattr(obj, '_%s' % arg)
        if isinstance(value, (type(None), list, basestring, datetime.date,
                              datetime.time)):
            data.append(repr(value))
        else:
            data.append(str(value))
    return "%s(%s)" % (obj.__class__.__name__, ', '.join(data))
40120
def char_repl(x):
    """"""
    r = ""
    for c in x:
        if ord(c) > 255:
            r += "?"
        else:
            r += c
    return r
182614
def repr_failure(self, excinfo):
        
        exc = excinfo.value
        cc = self.colors
        if isinstance(exc, NbCellError):
            msg_items = [
                cc.FAIL + "Notebook cell execution failed" + cc.ENDC]
            formatstring = (
                cc.OKBLUE + "Cell %d: %s\n\n" +
                "Input:\n" + cc.ENDC + "%s\n")
            msg_items.append(formatstring % (
                exc.cell_num,
                str(exc),
                exc.source
            ))
            if exc.inner_traceback:
                msg_items.append((
                    cc.OKBLUE + "Traceback:" + cc.ENDC + "\n%s\n") %
                    exc.inner_traceback)
            return "\n".join(msg_items)
        else:
            return "pytest plugin exception: %s" % str(exc)
908180
def exception_catcher(fn):
    
    exceptions = Queue.Queue()

    @wraps(fn)
    def wrapped(*args, **kwargs):
        try:
            ret = fn(*args, **kwargs)
        except Exception:
            exceptions.put(sys.exc_info())
            raise
        return ret

    def check():
        try:
            item = exceptions.get(block=False)
            klass, value, tb = item
            raise klass, value, tb
        except Queue.Empty:
            pass

    setattr(wrapped, 'check', check)
    return wrapped
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)
628599
def recursive_repr(func):
    """"""
    repr_running = set()

    @wraps(func)
    def wrapper(self):
        "Return ellipsis on recursive re-entry to function."
        key = id(self), get_ident()

        if key in repr_running:
            return '...'

        repr_running.add(key)

        try:
            return func(self)
        finally:
            repr_running.discard(key)

    return wrapper
150909
def _tuple_repr(data):
    """"""
    if len(data) == 1:
        return "(%s,)" % rpr(data[0])
    else:
        return "(%s)" % ", ".join([rpr(x) for x in data])
698103
def _error_repr(error):
    """"""
    error_repr = repr(error)
    if len(error_repr) > 200:
        error_repr = hash(type(error))
    return error_repr
1136482
def throws(exc):
    '''
    
    '''
    if not __CHECKING__:
        return lambda f: f

    def wrap(f):
        def call(*args, **kwd):
            res = f(*args, **kwd)
            # raise UncheckedExceptionError if exc is not automatically
            # registered by a function decorated with @catches(exc);
            # otherwise do nothing
            exc_checker.throwing(exc)
            return res
        call.__name__ = f.__name__
        return call
    return wrap