42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
import logging
|
|
import traceback
|
|
from fastapi import Request, status
|
|
from fastapi.responses import JSONResponse
|
|
# from fastapi import Request, status
|
|
|
|
from api.core.exception import ResponseException
|
|
|
|
logger = logging.getLogger('dcalc.exception')
|
|
|
|
|
|
def format_exception() -> str:
|
|
lines = traceback.format_exc().strip().splitlines()
|
|
if lines and lines[0].startswith('Traceback '):
|
|
lines = lines[1:]
|
|
return '\r'.join(lines)
|
|
|
|
|
|
async def all_exception_handler(request: Request, ex: Exception):
|
|
# api = str(request.url).split("api/")[1]
|
|
info = ''
|
|
if not isinstance(ex, ResponseException):
|
|
info = format_exception()
|
|
client_host = request.client.host if request.client else ''
|
|
if client_host != '127.0.0.1':
|
|
logger.error('Unhandled exception for %s', request.url.path, exc_info=(type(ex), ex, ex.__traceback__))
|
|
info = '服务器内部错误'
|
|
else:
|
|
info = ex.args[0]
|
|
# traceback.print_last(sys.exc_info())
|
|
return JSONResponse(
|
|
status_code=status.HTTP_200_OK,
|
|
# 一定要加
|
|
headers={'Access-Control-Allow-Origin': '*'},
|
|
content={
|
|
'code': 500,
|
|
'message': info,
|
|
# f"api:{api} \n \r{info}",
|
|
'data': [],
|
|
},
|
|
)
|