Python types.TracebackType() Examples

The following are 30 code examples of types.TracebackType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: _tblib.py    From satori with Apache License 2.0 18 votes vote down vote up
def as_traceback(self):
        if tproxy:
            return tproxy(TracebackType, self.__tproxy_handler)
        elif tb_set_next:
            f_code = self.tb_frame.f_code
            code = compile('\n' * (self.tb_lineno - 1) + 'raise __traceback_maker', self.tb_frame.f_code.co_filename, 'exec')
            if PY3:
                code = CodeType(
                    0, 0,
                    f_code.co_nlocals, f_code.co_stacksize, f_code.co_flags,
                    code.co_code, code.co_consts, code.co_names, code.co_varnames,
                    f_code.co_filename, f_code.co_name,
                    code.co_firstlineno, b"",
                    (), ()
                )
            else:
                code = CodeType(
                    0,
                    f_code.co_nlocals, f_code.co_stacksize, f_code.co_flags,
                    code.co_code, code.co_consts, code.co_names, code.co_varnames,
                    f_code.co_filename.encode(), f_code.co_name.encode(),
                    code.co_firstlineno, b"",
                    (), ()
                )

            try:
                exec(code, self.tb_frame.f_globals, {})
            except:
                tb = sys.exc_info()[2].tb_next
                tb_set_next(tb, self.tb_next and self.tb_next.as_traceback())
                try:
                    return tb
                finally:
                    del tb
        else:
            raise RuntimeError("Cannot re-create traceback !") 
Example #2
Source File: test_noop_span.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_span_error_report():
    tracer = Tracer()
    span = tracer.start_span('foo')
    error_message = 'unexpected_situation'

    with mock.patch.object(span, 'log_kv') as log_kv:
        with mock.patch.object(span, 'set_tag') as set_tag:
            try:
                with span:
                    raise ValueError(error_message)
            except ValueError:
                pass

            assert set_tag.call_count == 1
            assert set_tag.call_args[0] == (tags.ERROR, True)

            assert log_kv.call_count == 1
            log_kv_args = log_kv.call_args[0][0]
            assert log_kv_args.get(logs.EVENT, None) is tags.ERROR
            assert log_kv_args.get(logs.MESSAGE, None) is error_message
            assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError
            assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None),
                              ValueError)
            assert isinstance(log_kv_args.get(logs.STACK, None),
                              types.TracebackType) 
Example #3
Source File: parser.py    From tartiflette with MIT License 6 votes vote down vote up
def __exit__(
        self,
        exc_type: Optional[Type],
        exc_value: Optional[Exception],
        traceback: Optional[TracebackType],
    ) -> None:
        """
        Frees the resource related to the parsing of the query made by the
        libgraphqlparser library.
        :param exc_type: class of the exception potentially raised
        :param exc_value: instance of the exception potentially raised
        :param traceback: traceback of the exception potentially raised
        :type exc_type: Optional[Type]
        :type exc_value: Optional[Exception]
        :type traceback: Optional[TracebackType]
        """
        self._destroy_cb(self._c_parsed) 
Example #4
Source File: excepthook.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _make_excepthook(old_excepthook):
    # type: (Excepthook) -> Excepthook
    def sentry_sdk_excepthook(type_, value, traceback):
        # type: (Type[BaseException], BaseException, TracebackType) -> None
        hub = Hub.current
        integration = hub.get_integration(ExcepthookIntegration)

        if integration is not None and _should_send(integration.always_run):
            # If an integration is there, a client has to be there.
            client = hub.client  # type: Any

            with capture_internal_exceptions():
                event, hint = event_from_exception(
                    (type_, value, traceback),
                    client_options=client.options,
                    mechanism={"type": "excepthook", "handled": False},
                )
                hub.capture_event(event, hint=hint)

        return old_excepthook(type_, value, traceback)

    return sentry_sdk_excepthook 
Example #5
Source File: test_scope.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_scope_error_report():
    tracer = Tracer()
    scope = tracer.start_active_span('foo')
    error_message = 'unexpected_situation'

    with mock.patch.object(scope.span, 'log_kv') as log_kv:
        with mock.patch.object(scope.span, 'set_tag') as set_tag:
            try:
                with scope:
                    raise ValueError(error_message)
            except ValueError:
                pass

            assert set_tag.call_count == 1
            assert set_tag.call_args[0] == (tags.ERROR, True)

            assert log_kv.call_count == 1
            log_kv_args = log_kv.call_args[0][0]
            assert log_kv_args.get(logs.EVENT, None) is tags.ERROR
            assert log_kv_args.get(logs.MESSAGE, None) is error_message
            assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError
            assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None),
                              ValueError)
            assert isinstance(log_kv_args.get(logs.STACK, None),
                              types.TracebackType) 
Example #6
Source File: inspect.py    From meddle with MIT License 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example #7
Source File: req_tracker.py    From pex with Apache License 2.0 5 votes vote down vote up
def __exit__(
        self,
        exc_type,  # type: Optional[Type[BaseException]]
        exc_val,  # type: Optional[BaseException]
        exc_tb  # type: Optional[TracebackType]
    ):
        # type: (...) -> None
        self.cleanup() 
Example #8
Source File: _tblib.py    From satori with Apache License 2.0 5 votes vote down vote up
def install():
    try:
        import copy_reg
    except ImportError:
        import copyreg as copy_reg

    copy_reg.pickle(TracebackType, pickle_traceback)

# Added by gevent

# We have to defer the initialization, and especially the import of platform,
# until runtime. If we're monkey patched, we need to be sure to use
# the original __import__ to avoid switching through the hub due to
# import locks on Python 2. See also builtins.py for details. 
Example #9
Source File: _pydev_inspect.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example #10
Source File: RemoteDebugger.py    From oss-ftp with MIT License 5 votes vote down vote up
def wrap_info(info):
    "replace info[2], a traceback instance, by its ID"
    if info is None:
        return None
    else:
        traceback = info[2]
        assert isinstance(traceback, types.TracebackType)
        traceback_id = id(traceback)
        tracebacktable[traceback_id] = traceback
        modified_info = (info[0], info[1], traceback_id)
        return modified_info 
Example #11
Source File: inspect.py    From oss-ftp with MIT License 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example #12
Source File: inspect.py    From Computable with MIT License 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example #13
Source File: req_tracker.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __exit__(
        self,
        exc_type,  # type: Optional[Type[BaseException]]
        exc_val,  # type: Optional[BaseException]
        exc_tb  # type: Optional[TracebackType]
    ):
        # type: (...) -> None
        self.cleanup() 
Example #14
Source File: locks.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def __aexit__(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[types.TracebackType],
    ) -> None:
        self.release() 
Example #15
Source File: locks.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(
        self,
        exc_type: "Optional[Type[BaseException]]",
        exc_val: Optional[BaseException],
        exc_tb: Optional[types.TracebackType],
    ) -> None:
        self._obj.release() 
Example #16
Source File: testing.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        self.logger.removeFilter(self)
        if not typ and self.required and not self.matched:
            raise Exception("did not get expected log message") 
Example #17
Source File: testing.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _handle_exception(
        self, typ: Type[Exception], value: Exception, tb: TracebackType
    ) -> bool:
        if self.__failure is None:
            self.__failure = (typ, value, tb)
        else:
            app_log.error(
                "multiple unhandled exceptions in test", exc_info=(typ, value, tb)
            )
        self.stop()
        return True 
Example #18
Source File: debug.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example #19
Source File: iostream.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def close(
        self,
        exc_info: Union[
            None,
            bool,
            BaseException,
            Tuple[
                "Optional[Type[BaseException]]",
                Optional[BaseException],
                Optional[TracebackType],
            ],
        ] = False,
    ) -> None:
        """Close this stream.

        If ``exc_info`` is true, set the ``error`` attribute to the current
        exception from `sys.exc_info` (or if ``exc_info`` is a tuple,
        use that instead of `sys.exc_info`).
        """
        if not self.closed():
            if exc_info:
                if isinstance(exc_info, tuple):
                    self.error = exc_info[1]
                elif isinstance(exc_info, BaseException):
                    self.error = exc_info
                else:
                    exc_info = sys.exc_info()
                    if any(exc_info):
                        self.error = exc_info[1]
            if self._read_until_close:
                self._read_until_close = False
                self._finish_read(self._read_buffer_size, False)
            if self._state is not None:
                self.io_loop.remove_handler(self.fileno())
                self._state = None
            self.close_fd()
            self._closed = True
        self._signal_closed() 
Example #20
Source File: gen.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def handle_exception(
        self, typ: Type[Exception], value: Exception, tb: types.TracebackType
    ) -> bool:
        if not self.running and not self.finished:
            self.future = Future()
            future_set_exc_info(self.future, (typ, value, tb))
            self.run()
            return True
        else:
            return False


# Convert Awaitables into Futures. 
Example #21
Source File: simple_httpclient.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _handle_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> bool:
        if self.final_callback:
            self._remove_timeout()
            if isinstance(value, StreamClosedError):
                if value.real_error is None:
                    value = HTTPStreamClosedError("Stream closed")
                else:
                    value = value.real_error
            self._run_callback(
                HTTPResponse(
                    self.request,
                    599,
                    error=value,
                    request_time=self.io_loop.time() - self.start_time,
                    start_time=self.start_wall_time,
                )
            )

            if hasattr(self, "stream"):
                # TODO: this may cause a StreamClosedError to be raised
                # by the connection's Future.  Should we cancel the
                # connection more gracefully?
                self.stream.close()
            return True
        else:
            # If our callback has already been called, we are probably
            # catching an exception that is not caused by us but rather
            # some child of our callback. Rather than drop it on the floor,
            # pass it along, unless it's just the stream being closed.
            return isinstance(value, StreamClosedError) 
Example #22
Source File: websocket.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def log_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        assert typ is not None
        assert value is not None
        app_log.error("Uncaught exception %s", value, exc_info=(typ, value, tb)) 
Example #23
Source File: websocket.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def log_exception(
            self,
            typ: Optional[Type[BaseException]],
            value: Optional[BaseException],
            tb: Optional[TracebackType],
        ) -> None:
            pass 
Example #24
Source File: web.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def log_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        """Override to customize logging of uncaught exceptions.

        By default logs instances of `HTTPError` as warnings without
        stack traces (on the ``tornado.general`` logger), and all
        other exceptions as errors with stack traces (on the
        ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = [value.status_code, self._request_summary()] + list(value.args)
                gen_log.warning(format, *args)
        else:
            app_log.error(  # type: ignore
                "Uncaught exception %s\n%r",
                self._request_summary(),
                self.request,
                exc_info=(typ, value, tb),
            ) 
Example #25
Source File: inspect.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example #26
Source File: serializer.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __exit__(
        self,
        ty,  # type: Optional[Type[BaseException]]
        value,  # type: Optional[BaseException]
        tb,  # type: Optional[TracebackType]
    ):
        # type: (...) -> None
        self._ids.pop(id(self._objs.pop()), None) 
Example #27
Source File: utils.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def single_exception_from_error_tuple(
    exc_type,  # type: Optional[type]
    exc_value,  # type: Optional[BaseException]
    tb,  # type: Optional[TracebackType]
    client_options=None,  # type: Optional[Dict[str, Any]]
    mechanism=None,  # type: Optional[Dict[str, Any]]
):
    # type: (...) -> Dict[str, Any]
    if exc_value is not None:
        errno = get_errno(exc_value)
    else:
        errno = None

    if errno is not None:
        mechanism = mechanism or {}
        mechanism.setdefault("meta", {}).setdefault("errno", {}).setdefault(
            "number", errno
        )

    if client_options is None:
        with_locals = True
    else:
        with_locals = client_options["with_locals"]

    frames = [
        serialize_frame(tb.tb_frame, tb_lineno=tb.tb_lineno, with_locals=with_locals)
        for tb in iter_stacks(tb)
    ]

    rv = {
        "module": get_type_module(exc_type),
        "type": get_type_name(exc_type),
        "value": safe_str(exc_value),
        "mechanism": mechanism,
    }

    if frames:
        rv["stacktrace"] = {"frames": frames}

    return rv 
Example #28
Source File: utils.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def iter_stacks(tb):
    # type: (Optional[TracebackType]) -> Iterator[TracebackType]
    tb_ = tb  # type: Optional[TracebackType]
    while tb_ is not None:
        if not should_hide_frame(tb_.tb_frame):
            yield tb_
        tb_ = tb_.tb_next 
Example #29
Source File: utils.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __exit__(self, ty, value, tb):
        # type: (Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]) -> bool
        if ty is not None and value is not None:
            capture_internal_exception((ty, value, tb))

        return True 
Example #30
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def log_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        """Override to customize logging of uncaught exceptions.

        By default logs instances of `HTTPError` as warnings without
        stack traces (on the ``tornado.general`` logger), and all
        other exceptions as errors with stack traces (on the
        ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = [value.status_code, self._request_summary()] + list(value.args)
                gen_log.warning(format, *args)
        else:
            app_log.error(  # type: ignore
                "Uncaught exception %s\n%r",
                self._request_summary(),
                self.request,
                exc_info=(typ, value, tb),
            )