Flask全局异常处理
Contents
:::tip Flask自定义全局响应类 :::
api的设计中, 无论异常还是正常数据均需要服务器以json的格式返回, 为了对异常的统一管理, 同时为了后续更加方便的返回和验证数据, 自定义异常返回类.
设计异常数据的返回格式为:
{
"error_code": 999,
"msg": "sorry, we make a mistake",
"request": "POST /v1/client/register"
}
重写异常类
定义一个最基本的类, 供其它类继承, 取名为APIException继承HTTPException. 这个功能取一个单独文件存放,方便调用
-
返回特定的body信息, 需要重写get_body
-
指定返回类型, 需要重写get_headers
-
接收自定义的参数, 重写了__init__
-
同时定义了类变量作为几个默认参数(code 状态码,error_code 自定义错误码,msg 描述信息)
from flask import request, json
from werkzeug.exceptions import HTTPException
"""
HTTPException: 所有HTTP异常的基类。可以将此异常称为WSGI应用程序,
以呈现默认错误页面,或者您可以独立捕获其子类并呈现更好的错误消息。
"""
class APIException(HTTPException):
code = 500
msg = 'sorry, we made 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):
"""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]
自定义状态类
from application.libs.error import APIException
class Success(APIException):
code = 201
msg = 'ok'
error_code = 0
class DeleteSuccess(Success):
code = 202
error_code = -1
class ServerError(APIException):
code = 500
msg = 'sorry, we made a mistake (* ̄︶ ̄)!'
error_code = 999
class ClientTypeError(APIException):
# 400 401 403 404
# 500
# 200 201 204
# 301 302
code = 400
msg = 'client is invalid'
error_code = 1006
class ParameterException(APIException):
code = 400
msg = 'invalid parameter'
error_code = 1000
class NotFound(APIException):
code = 404
msg = 'the resource are not found O__O...'
error_code = 1001
class AuthFailed(APIException):
code = 401
error_code = 1005
msg = 'authorization failed'
class Forbidden(APIException):
code = 403
error_code = 1004
msg = 'forbidden, not in scope'
class DuplicateGift(APIException):
code = 400
error_code = 2001
msg = 'the current book has already in gift'