Search code examples
djangosentry

Making Sentry report 5XX errors in multi-thread environment


I am using Sentry to power up exception handling logging in my app.

The issue arises in the following code snippet:

@api_view(['POST'])
def testView(request):
    a = 1/0 # This error is reported to Sentry
    TestThread().start()
    return f_response_ok()

class TestThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(TestThread, self).__init__(*args, **kwargs)

    def run(self):
        print('Test')
        a = 1/0 # but this one is not
        return True

Is it possible to make Sentry report errors that have occurred in parallel thread?

And a bit off-topic: I would appreciate if someone provides a short comment as to whether such programming pattern is obsolete (and stuff like RabbitMQ should be used instead).


Solution

  • You could manually log them to sentry.

    https://docs.sentry.io/clients/python/#capture-an-error

    Assuming you are using django

    from raven.contrib.django.raven_compat.models import client
    
    class TestThread(threading.Thread):
    
        def __init__(self, *args, **kwargs):
            super(TestThread, self).__init__(*args, **kwargs)
    
        def run(self):
            print('Test')
            try:
                a = 1/0 # error is not reported in Sentry
            except: # I would suggest putting here expected exceptions
                client.captureException()
            return True