Skip to content

Commit 1dcd6ea

Browse files
committed
Added support to catch FastAPI exceptions
1 parent 364c1d2 commit 1dcd6ea

File tree

2 files changed

+30
-47
lines changed

2 files changed

+30
-47
lines changed

middleware/__init__.py

Lines changed: 29 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -84,49 +84,32 @@ def _auto_register(sender, **extra):
8484

8585

8686
# 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

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "middleware-io"
7-
version = "2.1.2rc6"
7+
version = "2.1.2rc7"
88
requires-python = ">=3.8"
99
description = "Middleware's APM tool enables Python developers to effortlessly monitor their applications, gathering distributed tracing, metrics, logs, and profiling data for valuable insights and performance optimization."
1010
authors = [{ name = "middleware-dev" }]

0 commit comments

Comments
 (0)