[TurboGears] ブログを作成する。その8
注意
この記事は、id:SumiTomohiko:20070122:1169487782の続きです。
エラー画面
現在のtgdiaryでは、処理中に例外が発生した場合、画面にスタックトレースが表示されます。これは格好悪いので、例外発生時には他の画面に遷移するようにします。遷移先は、/static/error.htmlとします。
@exception_handlerデコレータ
例外の捕捉には、@exception_handlerデコレータを使用します。これを用いると、例外発生時に、指定されたメソッドが実行されるようになります。
まず、例外発生時に実行するメソッドを記述します。これは、以下のようにします。
def _exception_handler(self, tg_exceptions=None): log.error(tg_exceptions) raise redirect('/static/error.html')
次に、@exposeしているメソッドに、@exception_handlerデコレータを追加します。例えば、以下のようにします。
@expose(template="tgdiary.templates.index") @exception_handler(_exception_handler) def index(self): import time return dict(now=time.ctime())
あとは、/static/error.htmlを用意します。今回は、以下のように簡単にすませます。
<html> <head> <title>エラー</title> </head> <body> <h1>エラー</h1> <p>エラーが発生しました。</p> </body> </html> <!-- vim: tabstop=4 shiftwidth=4 expandtab -->
以上で、例外発生時にはエラー画面に遷移するようになりました。