在view函數中,若是須要中斷request,能夠使用abort(500)或者直接raise exception。固然咱們還須要返回一個出錯信息給前端,因此須要定製一下ErrorHandler。通常只須要兩個個handler便可,一個是404錯誤,一個是500一類的服務器端錯誤。固然也能夠自定義錯誤。前端
# 在flask中能夠經過abort中斷觸發請求對應的狀態碼 from flask import abort @app.route('/') def index(): abort(401) # 請求到此即中斷,不會打印下面的語句,並返回HTTP狀態碼401 print '123'
下面是一份示例代碼,admin是一個藍本或者app,發生404錯誤或500錯誤,會返回一個Json對象給請求段。python
from flask import jsonify from . import admin @admin.errorhandler(404) def error_404(error): """這個handler能夠catch住全部abort(404)以及找不到對應router的處理請求""" response = dict(status=0, message="404 Not Found") return jsonify(response), 404 @admin.errorhandler(Exception) def error_500(error): """這個handler能夠catch住全部的abort(500)和raise exeception.""" response = dict(status=0, message="500 Error") return jsonify(response), 400 class MyError(Exception): """自定義錯誤類""" pass @admin.errorhandler(MyError) def MyErrorHandle(error): response = dict(status=0, message="400 Error") return jsonify(response), 400
在藍本中編寫錯誤處理程序有點不一樣,若是使用errorhandler
修飾器,那麼只有藍本中的錯誤纔會觸發。若是想註冊全局的錯誤處理程序,要用app_errorhandler
。json
例如:flask
from . import auth @auth.app_errorhandler(404) def error_404(error): response = dict(status=0, message="404 Not Found") return jsonify(response), 404
當咱們不是使用的工廠模式建立app時,app.errorhandler(401),便可捕捉全局401狀態;若使用了create_app方式建立app,則沒法進行捕捉,若想捕捉,能夠在藍圖中寫,如admin.errorhandler(401),即捕捉admin藍圖下全部401狀態碼,admin.app_errorhandler(401),則是捕捉的全局的401狀態碼,即其餘藍圖中的401狀態,也會被捕捉,進行處理服務器