File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1111 SPAStaticFiles ,
1212 custom_generate_unique_id ,
1313 lifespan ,
14+ setup_exception_handlers ,
1415 setup_logger ,
1516)
1617
5455
5556# Override the OpenAPI generation to customize operationId
5657override_openapi (app )
58+
59+ # Log unhandled exceptions through loguru and return a clean 500
60+ setup_exception_handlers (app )
Original file line number Diff line number Diff line change 88from zoneinfo import ZoneInfo
99
1010import simplejson
11- from fastapi import FastAPI
11+ from fastapi import FastAPI , Request
1212from fastapi .responses import JSONResponse
1313from fastapi .routing import APIRoute
1414from fastapi .staticfiles import StaticFiles
@@ -85,6 +85,21 @@ def custom_generate_unique_id(route: APIRoute) -> str:
8585 return f"{ route .tags [0 ]} -{ route .name } "
8686
8787
88+ def setup_exception_handlers (app : FastAPI ) -> None :
89+ @app .exception_handler (Exception )
90+ async def unhandled_exception_handler (request : Request , exc : Exception ) -> Response :
91+ route = request .scope .get ("route" )
92+ logger .bind (
93+ method = request .method ,
94+ path = request .url .path ,
95+ route = getattr (route , "path" , None ),
96+ client_host = request .client .host if request .client else None ,
97+ ).opt (exception = exc ).error ("Unhandled exception" )
98+ return KustomJSONResponse (
99+ status_code = 500 , content = {"detail" : "Internal Server Error" }
100+ )
101+
102+
88103def handle_special_types (obj : Any ) -> Any :
89104 print (f"handled type: { type (obj )} , { obj = } " )
90105 if isinstance (obj , BaseModel ):
You can’t perform that action at this time.
0 commit comments