2

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
Joabe da Luz
  • 1,030
  • 2
  • 18
  • 32

1 Answers1

2

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

Community
  • 1
  • 1
  • Nice, I put the try/except at the thread's caller and it's sending the email. Do you think I should delete this question because it seems like a duplicate o just edit and add the example? – Joabe da Luz Apr 03 '17 at 18:55