开发者

python exception handling

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

R开发者_StackOverflow中文版ich


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


#!/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 multiple exceptions for one block, e.g.:

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:

  • http://docs.python.org/tutorial/errors.html


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


Django Middleware is how you process exceptions in Django sites.

To catch all exceptions, you have to create a 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 your MIDDLEWARE_CLASSES setting:

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

Then you get control over what to do when encountering any kind of exception.

I think this answered your question. But you're probably better off overriding the 500.html template or the handler500 view. Notice that these views don't come into play until you set DEBUG to False in your project settings.


Try this:

try:
  # some code
except Exception, e:
  # log error with data from e
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜