Python exception handling

I am developing a Django site and am having difficulty finding the best way to handle exceptions. I was doing

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

It captures all exceptions, thereby guaranteeing that my site will not make 500 errors and the like. But, with my limited knowledge, I am losing the actual exception, and this creates a real pain for debugging. How to print the error? I am currently commenting on try: catch: and I see the error and fix it. There must be a better way!

Thanks in advance

Rich

+7
python
source share
5 answers

You catch the exception in the exception variable:

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

There are various ways to format exceptions, the logging module (which I assume you / Django uses) has support for formatting exceptions, and the exceptions themselves usually provide useful messages when rendering 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 "how" syntax to throw an exception that is supported in Python 2.6 and later. The output is higher:

 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 
+17
source share
 #!/usr/bin/env python import sys try: 0 / 0 except Exception, e: print >> sys.stderr, 'Hello %s' % e # Hello integer division or modulo by zero 

Note that you can catch several exceptions for a single block, for example:

 try: open(filename) except NameError, e: print >> sys.stderr, e except IOError, ioe: print >> sys.stderr, ioe 

More on exception handling can be found in this tutorial:

+4
source share

this can help

 try: raise Exception('spam', 'eggs') except Exception as inst: print type(inst) # the exception instance print inst.args # arguments stored in .args print inst # __str__ allows args to printed directly x, y = inst.args print 'x =', x print 'y =', y 
+3
source share

Try the following:

 try: // some code except Exception, e: // log error with data from e 
+1
source share

Django Middleware is how you handle exceptions on Django sites.

To catch all exceptions, you need to create Django middleware and create a process_exception method.

 from django.http import HttpResponse class SomeMiddleware(object): def process_exception(self, request, exception): 'Intercept exceptions' return HttpResponse('Hey! an error occurred', content_type='text/plain') 

then you add it to the MIDDLEWARE_CLASSES setting:

 MIDDLEWARE_CLASSES = ( # ... 'some.module.SomeMiddleware', ) 

Then you gain control over what to do when you encounter an exception.

I think this is the answer to your question. But you are probably better off redefining the 500.html template or handler500 view . Note that these views do not come into play until you set DEBUG to False in your project settings.

+1
source share

All Articles