You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
from apiflask import APIFlask, HTTPError
|
|
from apiflask.exceptions import _ValidationError
|
|
from iti.applications.common.utils import fail
|
|
from iti.applications.common.exceptions.biz_exp import BizException
|
|
from iti.applications.common.exceptions.permission import PermissionDeniedException
|
|
|
|
|
|
def init_error_handler(app: APIFlask):
|
|
"""
|
|
全局异常处理
|
|
"""
|
|
|
|
@app.errorhandler(Exception)
|
|
def handle_exception(error):
|
|
"""
|
|
未处理的异常处理
|
|
"""
|
|
app.logger.error("服务器错误", error, stack_info=True)
|
|
return fail(message="服务器错误", code=500, data=str(error))
|
|
|
|
@app.errorhandler(400)
|
|
def handle_400(error):
|
|
"""
|
|
参数错误
|
|
"""
|
|
app.logger.error("参数错误", error, stack_info=True)
|
|
return fail(
|
|
message=error.data.message
|
|
if error.data and "message" in error.data
|
|
else "参数错误",
|
|
code=400,
|
|
data=str(error),
|
|
)
|
|
|
|
@app.errorhandler(BizException)
|
|
def handle_biz_exception(error: BizException):
|
|
"""
|
|
业务异常处理
|
|
"""
|
|
app.logger.error(f"业务异常: {error}")
|
|
return fail(error.message, code=error.code, data=error.data)
|
|
|
|
@app.errorhandler(PermissionDeniedException)
|
|
def handle_permission_denied_exception(error: PermissionDeniedException):
|
|
"""
|
|
权限不足异常处理
|
|
"""
|
|
app.logger.error(f"权限不足: {error}")
|
|
return fail(message=error.message, code=error.code)
|
|
|
|
@app.error_processor
|
|
def handler_http_error(error: HTTPError):
|
|
"""
|
|
http异常处理
|
|
"""
|
|
if isinstance(error, _ValidationError):
|
|
app.logger.error(f"参数验证错误: {error.detail}")
|
|
error.message = "参数验证错误"
|
|
else:
|
|
app.logger.error(
|
|
f"HTTP异常: {error.message} {error.status_code} {error.detail} {error.headers} {error.extra_data}"
|
|
)
|
|
return (
|
|
fail(message=error.message, code=error.status_code, data=error.detail),
|
|
200,
|
|
error.headers,
|
|
)
|