2011-01-04 43 views
6

私はDjangoサイトを開発しており、例外処理を行うための最良の方法を見つけようと努力してきました。私はやっているPython例外処理

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

これは私のサイトが500エラーなどを提供しないようにするため、すべての例外をキャッチします。しかし、私の限られた知識で、私は実際の例外を失いつつあり、デバッグするのに本当の苦労をしています。発生したエラーをどのように印刷するのですか?現在私はtry:catch:をコメントアウトし、エラーを見て修正します。より良い方法が必要です!事前に

おかげ

リッチ

+0

を助けることができますかこの種のプログラミングを示すチュートリアルへの引用やリンクを提供できますか?それは悪い習慣と考えられています。私はあなたがこれをどこで学んだのか知りたい。 –

+4

@ S.Lott:そのような人に降りるのではなく、何か別のアプローチを提供し、それが悪い習慣とみなされる理由を説明する方が良いかもしれません。 – magiconair

答えて

1

はこれを試してみてください:

try: 
    // some code 
except Exception, e: 
    // log error with data from e 
15

あなたは例外変数に例外をキャッチ:

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

例外をフォーマットするためのさまざまな方法があります。 、ロギングモジュール(私はあなた/ Djangoが使用すると仮定します)は、excep通常は、文字列にレンダリングされるときに例外メッセージ自体が有用なメッセージを表示します。ここで

は一例です:

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) 

この例では、Python 2.6以降でサポートされている例外をキャッチする構文「と」新しいを使用しています。上記の出力は、次のとおりです。あなたが一つのブロックのための複数の例外をキャッチすることができ

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 
4
#!/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 

注、例えば:

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

例外処理の詳細は、このチュートリアルで見つけることができ

1

Django Middlewareは、Djangoサイトで例外を処理する方法です。

例外をすべてキャッチするには、Djangoミドルウェアを作成してprocess_exceptionメソッドを作成する必要があります。そして、あなたは例外のいずれかの種類に遭遇したときに何をすべきかを制御し得る

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

を:

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') 

あなたが設定あなたのMIDDLEWARE_CLASSESに追加します。

これはあなたの質問に答えたと思います。しかし、あなたはおそらくoverriding the 500.html template or the handler500 viewより良いでしょう。これらのビューは、プロジェクト設定でDEBUGをFalseに設定するまで表示されません。

3

これはあなたがそのような "裸の" `except`文を見たことがありますか?

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