1 from flask import jsonify 2 from . import admin 3 @admin.errorhandler(404) 4 def error_404(error): 5 """这个handler能够catch住全部abort(404)以及找不到对应router的处理请求""" 6 response = dict(status=0, message="404 Not Found") 7 return jsonify(response), 404 8 @admin.errorhandler(Exception) 9 def error_500(error): 10 """这个handler能够catch住全部的abort(500)和raise exeception.""" 11 response = dict(status=0, message="500 Error") 12 return jsonify(response), 400 13 class MyError(Exception): 14 """自定义错误类""" 15 pass 16 @admin.errorhandler(MyError) 17 def MyErrorHandle(error): 18 response = dict(status=0, message="400 Error") 19 return jsonify(response), 400
1 from . import auth 2 @auth.app_errorhandler(404) 3 def error_404(error): 4 response = dict(status=0, message="404 Not Found") 5 return jsonify(response), 404
如下代码为我本身项目中的实现:html
首先新建一个error.py文件json
1 import json 2 from flask import Blueprint, Response 3 4 exception = Blueprint('exception',__name__) 5 6 @exception.app_errorhandler(404) 7 def error_404(error): 8 """这个handler能够catch住全部abort(404)以及找不到对应router的处理请求""" 9 res = {"status": 404, "message": "404错误,找不到对应router"} 10 return Response(json.dumps(res), mimetype='application/json') 11 12 @exception.app_errorhandler(405) 13 def error_405(error): 14 """这个handler能够catch住全部abort(405)以及请求方式有误的请求""" 15 res = {"status": 405, "message": "请求方式有误"} 16 return Response(json.dumps(res), mimetype='application/json') 17 18 # @exception.app_errorhandler(Exception) 19 # def error_500(error): 20 # """这个handler能够catch住全部的abort(500)和raise exeception.""" 21 # res = {"status": 500, "message": "系统内部错误"} 22 # return Response(json.dumps(res), mimetype='application/json') 23 24 class MyError(Exception): 25 """自定义错误类""" 26 pass
而后在flask启动文件中新增以下代码:flask
1 # 导入error.py文件中的exception蓝图 2 from error import exception 3 from flask import Flask, request, Response 4 5 6 app = Flask(__name__) 7 # 注册蓝图,并指定其对应的前缀(url_prefix) 8 app.register_blueprint(exception, url_prefix='/error') 9 # 如下能够写业务代码 10 11 12 if __name__ == '__main__': 13 app.run(host='0.0.0.0', port=8089, debug=False, threaded=True)