#重写异常类
def register_exception(app: FastAPI):
# 捕获全局异常
@user1r(Exception)
async def all_exception_handler(request: Request, exc: Exception):
# #query参数:
# query_data = request.query_params
# print(query_data)
request_data = await request.json()
print(request_data)
log_msg = f"捕获到系统错误:请求路径:{request.url.path}\n错误信息:{traceback.format_exc()}"
mylog.error(log_msg)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=jsonable_encoder({
"responseCode": Status.FAIL.get_code(),
"responseMsg": Status.FAIL.get_msg()
},
))
想要做的功能是,捕获到全局异常时,将接口的请求参数写进去日志文件中,但是打印 request_data = await request.json() 就已经报错了。
附详细报错:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 396, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in call
return await self.app(scope, receive, send)
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\uvicorn\middleware\debug.py", line 96, in call
raise exc from None
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\uvicorn\middleware\debug.py", line 78, in call
await self.app(scope, receive, inner_send)
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\fastapi\applications.py", line 199, in call
await super().call(scope, receive, send)
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\applications.py", line 111, in call
await self.middleware_stack(scope, receive, send)
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\middleware\errors.py", line 172, in call
response = await self.handler(request, exc)
File "E:\bmTest_fastapi\utils\exception_utils.py", line 57, in all_exception_handler
request_data = await request.json()
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\requests.py", line 226, in json
body = await self.body()
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\requests.py", line 219, in body
async for chunk in self.stream():
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\requests.py", line 204, in stream
message = await self._receive()
File "C:\Users\junjie\AppData\Local\Programs\Python\Python37\lib\site-packages\starlette\requests.py", line 167, in empty_receive
raise RuntimeError("Receive channel has not been made available")
RuntimeError: Receive channel has not been made available
2021-03-08 14:36:57,331 - [ERROR] - run_asgi - [msg]:Exception in ASGI application