Joabe da Luz
Joabe da Luz

Reputation: 1020

How to catch exceptions that happened in a python threading.Thread execution?

Basically I would like to receive an email using the Django mail_admins when a not handled exception happen inside a Thread. Currently, I have a view that handles post requests and it looks like that:

import threading
# ...
def post(self, request, *args, **kwargs):
    # Some stuff...
    for message in entry['messaging']:
         t = threading.Thread(
         target=self.local_handler,
              args=(message, page_id)
         )
         t.setDaemon(True)
         t.start()
    # Some more stuff

Right now, when any Exception happens and it's not handled, it will be shown in the server log. Something like this:

Exception in thread Thread-2:
Traceback (most recent call last):
...

Is there a way to receive those tracebacks by email? I was receiving emails before I started using threads, but now it's doesn't work anymore.

EDIT:

As @ivan-miljkovic suggested in his answer linking the a similar question the solution worked for me.

So, basically I have to catch the exception inside the thread function:

import threading
from django.core.mail import mail_admins
# ...

def local_handler(self, message, page_id):
    try:
       # do stuff
    except: # Any not handled exception will send an email with the traceback
       import traceback
       details = traceback.format_exc()
       mail_admins('Background exception happened', details)

def post(self, request, *args, **kwargs):
    # Some stuff...
    for message in entry['messaging']:
         t = threading.Thread(
         target=self.local_handler,
              args=(message, page_id)
         )
         t.setDaemon(True)
         t.start()
    # Some more stuff

Upvotes: 2

Views: 15192

Answers (1)

Ivan Miljkovic
Ivan Miljkovic

Reputation: 99

Try this one.

When you catch it in thread's caller, you can easily email it like you used to do.

Catch a thread's exception in the caller thread in Python

Upvotes: 2

Related Questions