异常自定义
import json
from flask import request
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
code = None
msg = None
def __init__(self, msg=None):
self.msg = msg or self.__class__.__name__
super(APIException, self).__init__(msg, None)
def get_body(self, environ=None):
body = dict(
error_msg=self.msg,
error_code=self.code,
request=request.method + ' ' + self.get_url_no_param()
)
return json.dumps(body)
def get_headers(self, environ=None):
"""Get a list of headers."""
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]
def gen_error(name: str, err_code: int) -> APIException:
base_cls = (APIException,)
cls_attr = {'code': err_code}
return type(name, base_cls, cls_attr)
NotFoundError = gen_error('NotFoundError', 404)
InternalError = gen_error('InternalError', 500)
ParamsError = gen_error('ParamsError', 1001)
DataError = gen_error('DataError', 1002)
DoseNotExist = gen_error('DoseNotExist', 1003)
ReachUpperLimit = gen_error('ReachUpperLimit', 1004)
PermissionDenied = gen_error('PermissionDenied', 1005)
Timeout = gen_error('Timeout', 1006)
Expired = gen_error('Expired', 1007)
NotAllowRequestType = gen_error('NotAllowRequestType', 1008)
RestrictOperation = gen_error('RestrictOperation', 1009)
UnKnownError = gen_error('UnKnownError', 1020)
Flask全局处理
@app.errorhandler(Exception)
def framework_error(e):
my_error_log.logger.error(e)
if isinstance(e, APIException):
return e
if isinstance(e, HTTPException):
return UnKnownError()
else:
return InternalError()
https://zhuanlan.zhihu.com/p/142843332