Skip to content

Typing: Accept BaseException for set_error and related functions #290

Open

Description

@Mr0grog

Right now, the error argument for set_error(), send_error(), and send_error_with_context() are typed as Exception:

def set_error(error: Exception, span: Span | None = None) -> None:
span = span or trace.get_current_span()
span.set_status(Status(StatusCode.ERROR))
span.record_exception(error, attributes={"appsignal.alert_this_error": True})
def send_error(error: Exception) -> None:
with send_error_with_context(error):
pass
_send_error_tracer = trace.get_tracer("Appsignal.send_error")
@contextmanager
def send_error_with_context(error: Exception) -> Iterator[Span]:
name = error.__class__.__name__
# Passing an empty context ensures the new span does not use the current
# global context, meaning it will be the root span of a new trace, not a
# child of the current span and trace in the global context:
with _send_error_tracer.start_as_current_span(name, context=Context()) as span:
set_error(error, span)
yield span

However, a lot of Python APIs dealing with exception information are typed as BaseException in most stubs/type checkers (e.g. sys.exc_info() or logging.LogRecord.exc_info). When handling this kind of data and translating it into calls to AppSignal, it would be convenient if AppSignal’s functions accepted BaseException instead of Exception (as far as I’m aware, there’s no difference in their interfaces; Exception exists purely to distinguish error types that should always exit/crash from others in the class hierarchy).

As it currently stands, most type checkers will flag this as a problem:

from appsignal import set_error
from logging import Handler, LogRecord

class MyHandler(Handler):
    def emit(self, record: LogRecord) -> None:
        if record.exc_info and record.exc_info[1] is not None:
            set_error(record.exc_info[1]) # <-- Argument of type "BaseException"
                                          #     cannot be assigned to parameter
                                          #     "error" of type "Exception" in
                                          #     function "set_error"

It would be nice if that just worked without needing to add extra code or comments to ignore the type errors.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions