+1 vote

I am developing a Django site and have been having trouble trying to work out the best way to do exception handling. I have been doing

try:
    Some code
except:
    log error in my own words, i.e 'Some code' failed to execute
    Some other code

This catches all exceptions thus ensuring my site does not deliver 500 errors and such like. But, with my limited knowledge I am losing the actual exception and it is making it a real pain to debug. How do I print the error that occured? Currently I comment out try: catch: and see the error and fix it. There must be a better way!

Thanks in advance 

in Python by

1 Answer

0 votes
Best answer

You catch the exception in an exception variable:

try:
    # some code
except Exception, e:
    # Log the exception.

There are various ways to format the exception, the logging module (which I assume you/Django uses) has support to format exceptions, and the exceptions themselves usually render useful messages when rendered to strings.

Here is an example:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')

try:    
    1/0
except Exception as e:
    logging.exception(e)

This example uses the new "as" syntax to catch the exception, supported in Python 2.6 and later. The output of the above is:

DEBUG:root:This message should go to the log file
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
  File "untitled-1.py", line 6, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
by
selected by