在flask中如何统一处理异常以及400 500页面
异常类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
from flask import jsonify, render_template from app import app
class ExceptionCommon(Exception): status_code = 400 def __init__(self, message=None, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload
def to_dict(self): rv = dict(self.payload or ()) rv['status_code'] = self.status_code rv['message'] = self.message return rv
@app.errorhandler(ExceptionCommon) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response
@app.errorhandler(500) def handle_500(e): return render_template('500.html'), 404
@app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404
|
如何使用
1 2 3 4 5 6 7 8 9 10 11
| @auth.route('/logout', methods=('GET', 'POST')) @login_required def logout(): """ 注销登录,解除会话 logout_user() :return: """ xxx raise ExceptionCommon("错误原因") return redirect(url_for("auth.login"))
|
在整个web项目中使用
上述@app.errorhandler
这个errorhandler处理器注册在app上,只能对app使用
1 2 3 4 5
| @app.errorhandler(ExceptionCommon) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response
|
修改为以下内容@comm.app_errorhandler
需要注册comm的蓝本
1 2 3 4 5
| @comm.app_errorhandler(ExceptionCommon) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response
|