Преглед изворни кода

add: fastapi global exception handler

Azure пре 1 година
родитељ
комит
ce04a1306a
1 измењених фајлова са 25 додато и 20 уклоњено
  1. 25 20
      module/server/app.py

+ 25 - 20
module/server/app.py

@@ -1,19 +1,30 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+from contextlib import asynccontextmanager
+
 import argparse
-from fastapi import FastAPI
+from fastapi import FastAPI, Request
 from fastapi.middleware.cors import CORSMiddleware
 
 from module.logger import logger
 
 from module.server.home_router import home_app
 from module.server.script_router import script_app
+from starlette import status
+from starlette.responses import JSONResponse
+
 
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+    await on_startup()
+    yield
+    await on_shutdown()
 app = FastAPI(
     title='OAS',
     description='OAS web service',
     version='0.0.0',
+    lifespan=lifespan,
 )
 
 app.add_middleware(
@@ -27,30 +38,25 @@ app.add_middleware(
 app.include_router(home_app)
 app.include_router(script_app)
 
-@app.on_event("startup")
-async def startup_event():
-    logger.info('OAS web service startup done')
-    pass
-
-@app.on_event("shutdown")
-async def shutdown_event():
-    logger.info('OAS web service shutdown done')
-
-
-
-
-
-
-
-
-
-
 
+async def on_startup():
+    logger.info('OAS web service startup done')
 
 
+async def on_shutdown():
+    logger.info('OAS web service shutdown done')
 
 
+@app.exception_handler(Exception)
+async def global_exception_handler(request: Request, exc: Exception):
+    logger.error(f"Internal Server Error: {exc}")
 
+    return JSONResponse(
+        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+        content={
+            'message': ', '.join([arg for arg in exc.args])
+        },
+    )
 
 
 def fastapi_app():
@@ -71,5 +77,4 @@ def fastapi_app():
     )
     args, _ = parser.parse_known_args()
 
-
     return app