tfse-app-api-v0.2/Utils/ErrorUtil.py

102 lines
2.5 KiB
Python
Raw Normal View History

2022-04-06 04:30:30 +08:00
import time
import traceback
from flask import request
2022-06-06 13:37:09 +08:00
from werkzeug.exceptions import BadRequest
2022-04-06 04:30:30 +08:00
from DBHelper.MongoHelper import MongoHelper
2022-06-06 13:37:09 +08:00
def get_req_detail(req, param_type):
"""
获取请求参数信息
若异常请求则返回空字符串
"""
try:
if param_type == 'args':
return req.args.__str__()
elif param_type == 'json':
return req.json.__str__()
else:
return ''
except BadRequest:
return ''
class JustThrowError(RuntimeError):
"""自定义抛出异常信息"""
def __init__(self, error_info):
self.error_info = error_info
def __str__(self):
return self.error_info
class APIReturnError(RuntimeError):
"""接口返回异常信息"""
def __init__(self, error_info, status_code):
self.error_info = error_info # 异常信息
self.status_code = status_code # 状态码
def __str__(self):
return self.error_info
class AttrCheckError(RuntimeError):
"""属性检查异常"""
def __init__(self, error_info):
self.error_info = error_info
def __str__(self):
return self.error_info
2022-04-11 10:42:46 +08:00
class CheckFailed(RuntimeError):
2022-04-11 11:19:35 +08:00
"""检查异常"""
2022-04-06 04:30:30 +08:00
def __init__(self, failed_info, status_code):
self.failed_info = failed_info # 失败信息
self.status_code = status_code # 状态码
def __str__(self):
return self.failed_info
def log_error(self):
db = MongoHelper("tfse_v0.21")
info = {
"ip": request.remote_addr,
"request_info": {
"path": request.path,
"method": request.method,
"headers": request.headers.__str__(),
2022-06-06 13:37:09 +08:00
"args": get_req_detail(request, 'args'),
"json": get_req_detail(request, 'json')
2022-04-06 04:30:30 +08:00
},
"traceback": traceback.format_exc(),
"exception": type(self).__name__,
"is_solved": "no",
"time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
}
db.insert_single_data(
"日志",
"异常日志",
info
)
2022-04-11 10:42:46 +08:00
class LogConditionCheckFailed(CheckFailed):
2022-06-06 13:37:09 +08:00
"""直接记录检查异常"""
2022-04-11 10:42:46 +08:00
def __init__(self, failed_info, status_code):
self.failed_info = failed_info # 失败信息
self.status_code = status_code # 状态码
self.log_error()
class ReturnConditionCheckFailed(CheckFailed):
2022-06-06 13:37:09 +08:00
"""条件检查失败 抛出异常 接口返回失败原因和状态码"""