Skip to content

Commit 364c1d2

Browse files
committed
Updated stack trace sequence + Added internal file flag
1 parent 0440ebc commit 364c1d2

File tree

3 files changed

+59
-4
lines changed

3 files changed

+59
-4
lines changed

middleware/__init__.py

+47
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,50 @@ def _auto_register(sender, **extra):
8383
appcontext_pushed.connect(_auto_register)
8484

8585

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()

middleware/distro.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,23 @@ def custom_record_exception(span: Span, exc: Exception):
134134

135135
for (frame, _), (filename, lineno, func_name, _) in zip(traceback.walk_tb(exc_tb), tb_details):
136136
function_details = extract_function_code(frame, lineno) if frame else "Function source not found."
137-
138-
stack_info.append({
137+
138+
stack_entry = {
139139
"exception.file": filename,
140140
"exception.line": lineno,
141141
"exception.function_name": func_name,
142142
"exception.function_body": function_details["function_code"],
143143
"exception.start_line": function_details["function_start_line"],
144144
"exception.end_line": function_details["function_end_line"],
145-
})
145+
}
146+
147+
# Check if the file is from site-packages
148+
if "site-packages" in filename:
149+
stack_entry["exception.is_file_internal"] = "true"
150+
else:
151+
stack_entry["exception.is_file_internal"] = "false"
152+
153+
stack_info.insert(0, stack_entry) # Prepend instead of append
146154

147155
# Determine if the exception is escaping
148156
current_exc = sys.exc_info()[1] # Get the currently active exception

pyproject.toml

+1-1
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.2rc5"
7+
version = "2.1.2rc6"
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)