Flask ではエラー発生時の動作をカスタマイズできる。404 や 500 などの HTTP エラーに対して、独自のエラーページを表示することが可能である。
エラーハンドラの登録
@app.errorhandler デコレータでエラーハンドラを登録する。
from flask import Flask, render_template app = Flask(__name__) @app.errorhandler(404) def page_not_found(error): return render_template('errors/404.html'), 404 @app.errorhandler(500) def internal_server_error(error): return render_template('errors/500.html'), 500
ハンドラ関数はエラーオブジェクトを受け取り、レスポンスとステータスコードを返す。ステータスコードを明示的に返さないと 200 になってしまうので注意が必要である。
エラーテンプレートの例
<!-- templates/errors/404.html --> <!DOCTYPE html> <html> <head> <title>Page Not Found</title> </head> <body> <h1>404 - Page Not Found</h1> <p>The page you are looking for does not exist.</p> <a href="/">Go back to home</a> </body> </html>
abort によるエラー発生
意図的にエラーを発生させるには abort 関数を使う。
from flask import abort @app.route('/admin') def admin(): if not current_user.is_admin: abort(403) return 'Admin page'
abort(403) を呼ぶと、処理が中断されて 403 エラーハンドラが実行される。
例外クラスのハンドリング
HTTP エラーコードだけでなく、Python の例外クラスもハンドリングできる。
@app.errorhandler(ValueError) def handle_value_error(error): return {'error': str(error)}, 400
Blueprint でのエラーハンドラ
Blueprint にもエラーハンドラを登録できる。ただし、Blueprint のエラーハンドラはその Blueprint 内で発生したエラーにのみ適用される。
from flask import Blueprint api_bp = Blueprint('api', __name__) @api_bp.errorhandler(404) def api_not_found(error): return {'error': 'Resource not found'}, 404
アプリケーション全体に適用するエラーハンドラは app.errorhandler で登録する。