Thorvald
Thorvald

Reputation: 665

Custom exception python + Sentry stacktrace

I have a flask application where I've created some custom exceptions, the idea is that I want to create alerts based on these exceptions eventually. Right now, capturing the exception works, but the stack trace doesn't follow.

class SentryMailError(Exception):
    """Errors related to sending emails"""
    def __init__(self, err):
        super().__init__(err)

In X function, I want to be able to run:

from sentry_sdk import capture_exception
    def randomfunc():
        try:
           division_by_zero = 1 / 0
        except as err:
           capture_exception(SentryMaiLError(err)) # no stack trace
           capture_exception(err) # stack trace, but not able to use my custom error

And still keep the stacktrace, but no stack trace ends up being available. What am I doing wrong?

Upvotes: 0

Views: 1998

Answers (2)

Thorvald
Thorvald

Reputation: 665

This solved things for me:

class SentryMailError(Exception):
    """Custom Exception for sentry"""
    def __init__(self, err):
        self.__traceback__ = err.__traceback__

And to capture:

except Exception as err:
   capture_exception(SentryMailError(err))

Not sure if this is ideal though.. I'm just setting the traceback from the exception onto my custom exception, the stracktrace will follow onto Sentry.

Upvotes: 1

Serjx86
Serjx86

Reputation: 530

I am not quite sure what is the cause for stack trace being lost, but I am guessing it has something to do with your reimplementation of the __init__ for your custom exception that has no pass through *arg, **kwarg.

A simpler and a pythonic code could be

class SentryMailError(Exception):
    ...


from sentry_sdk import handle_my_exception, handle_all_exceptions


def random_func():
    try:
       division_by_zero = 1 / 0
    except SentryMaiLError as e:
       handle_my_exception(e)
    except Exception as e:
       handle_all_exceptions(e)

the except Exception as e: is a bad form, as it captures too general an exception, but it may be acceptable in high level handlers for requests that will generate http 500 response, for example.

Upvotes: 0

Related Questions