具体源码:https://github.com/LMFrank/Flask_api
自定义错误返回
Flask_api/app/libs/error.py
from flask import request, json
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
code = 500
msg = 'Sorry, we make a mistake!'
error_code = 999
def __init__(self, msg=None, code=None, error_code=None, headers=None):
if code:
self.code = code
if error_code:
self.error_code = error_code
if msg:
self.msg = msg
super(APIException, self).__init__(msg, None)
def get_body(self, environ=None):
body = dict(
msg=self.msg,
error_code=self.error_code,
request=request.method + ' ' + self.get_url_no_param()
)
text = json.dumps(body)
return text
def get_headers(self, environ=None):
return [('Content-Type', 'application/json')]
@staticmethod
def get_url_no_param():
full_path = str(request.full_path)
main_path = full_path.split('?')
return main_path[0]
HTTPException
中返回的是满足HTTP协议的数据,当我们需要统一接口的错误返回时可以继承
werkzeug
包内的
HTTPException
,重写构造函数、
get_body
和
get_headers
方法,使返回数据能够被序列化。
自定义错误类型
Flask_api/app/libs/error_code.py
## 示例
from app.libs.error import APIException
class ParameterException(APIException):
code = 400
msg = 'invalid parameter'
error_code = 1000
class NotFound(APIException):
code = 404
msg = 'the resource are not found...'
error_code = 1001
class AuthFailed(APIException):
code = 401
msg = 'authorization failed'
error_code = 1002
AOP思想解决全局异常返回
flask_api/ginger/ginger.py
from werkzeug.exceptions import HTTPException
from app import create_app
from app.libs.error import APIException
from app.libs.error_code import ServerError
app = create_app()
@app.errorhandler(Exception)
def framework_error(e):
if isinstance(e, APIException):
return e
if isinstance(e, HTTPException):
code = e.code
msg = e.description
error_code = 1007
return APIException(msg, code, error_code)
else:
# log
if not app.config['DEBUG']:
return ServerError()
else:
raise e
利用
errorhandler
装饰器去包装我们自定义的异常返回函数,将
APIException
、
HTTPException
加入全局判断。
版权声明:本文为LMFranK原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。