title: How to catch exceptions that happened in a python threading.Thread execution?
body: <p>Basically I would like to receive an email using the Django <code>mail_admins</code> when a not handled exception happen inside a Thread. Currently, I have a view that handles post requests and it looks like that:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Right now, when any Exception happens and it's not handled, it will be shown in the server log. Something like this:</p>
  
  <pre><code>Exception in thread Thread-2:
  Traceback (most recent call last):
  ...
  </code></pre>
  
  <p>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.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>As @ivan-miljkovic suggested in his answer linking the a similar question  the solution worked for me.</p>
  
  <p>So, basically I have to catch the exception inside the thread function:</p>
  
  <pre><code>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
  </code></pre>