@@ -84,49 +84,32 @@ def _auto_register(sender, **extra):
84
84
85
85
86
86
# Automatic exception handling for FastAPI
87
- # import sys
88
- # import traceback
89
- # from fastapi import FastAPI, Request
90
- # from starlette.middleware.base import BaseHTTPMiddleware
91
- # from starlette.exceptions import HTTPException as StarletteHTTPException
92
-
93
- # async def fastapi_exception_handler(request: Request, exc: Exception):
94
- # print("111 FastAPI _capture_exception Unhandled exception detected.")
95
- # """Handles unhandled exceptions globally in FastAPI."""
96
- # exc_type, exc_value, exc_traceback = sys.exc_info()
97
- # if exc_type and exc_value and exc_traceback:
98
- # record_exception(exc_type, exc_value, exc_traceback)
99
- # return StarletteHTTPException(status_code=500, detail="Internal Server Error")
100
-
101
- # class ExceptionMiddleware(BaseHTTPMiddleware):
102
- # print("222 FastAPI _capture_exception Unhandled exception detected.")
103
- # """Middleware to capture unhandled exceptions in FastAPI."""
104
- # async def dispatch(self, request, call_next):
105
- # print("3333 FastAPI _capture_exception Unhandled exception detected.")
106
- # try:
107
- # return await call_next(request)
108
- # except Exception as e:
109
- # exc_type, exc_value, exc_traceback = sys.exc_info()
110
- # if exc_type and exc_value and exc_traceback:
111
- # record_exception(exc_type, exc_value, exc_traceback)
112
- # raise e
113
-
114
- # def try_register_fastapi_handler(app: FastAPI):
115
- # """Registers the exception handler automatically when FastAPI is detected."""
116
- # app.add_exception_handler(Exception, fastapi_exception_handler)
117
- # app.add_middleware(ExceptionMiddleware)
118
- # print("✅ FastAPI error handler registered automatically.")
119
-
120
- # def auto_register_fastapi():
121
- # """Automatically detect FastAPI and register the handler."""
122
- # if "fastapi" in sys.modules:
123
- # app = None
124
- # for obj in sys.modules["fastapi"].__dict__.values():
125
- # if isinstance(obj, type) and issubclass(obj, FastAPI):
126
- # app = obj()
127
- # break
128
- # if app:
129
- # try_register_fastapi_handler(app)
130
-
131
- # # Try auto-registering when the package is imported
132
- # auto_register_fastapi()
87
+ from starlette .middleware .base import BaseHTTPMiddleware
88
+ from starlette .requests import Request
89
+ from starlette .responses import JSONResponse
90
+
91
+ class ExceptionMiddleware (BaseHTTPMiddleware ):
92
+ """Middleware to catch unhandled exceptions globally."""
93
+ async def dispatch (self , request : Request , call_next ):
94
+ try :
95
+ return await call_next (request )
96
+ except Exception as exc :
97
+ exc_type , exc_value , exc_traceback = exc .__class__ , exc , exc .__traceback__
98
+ record_exception (exc_type , exc_value , exc_traceback )
99
+
100
+ return JSONResponse (
101
+ status_code = 500 ,
102
+ content = {"detail" : "Internal Server Error" },
103
+ )
104
+
105
+ from fastapi import FastAPI
106
+ # from starlette.middleware import ExceptionMiddleware
107
+
108
+ _original_init = FastAPI .__init__
109
+
110
+ def new_fastapi_init (self , * args , ** kwargs ):
111
+ _original_init (self , * args , ** kwargs )
112
+ print ("✅ FastAPI instance created, registering ExceptionMiddleware." )
113
+ self .add_middleware (ExceptionMiddleware )
114
+
115
+ FastAPI .__init__ = new_fastapi_init
0 commit comments