Skip to content

Commit 0440ebc

Browse files
committed
Automatic exception handling for flask apps
1 parent 03eec54 commit 0440ebc

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

middleware/__init__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,28 @@ def _uninstrument(self, **kwargs):
5858
# Load the instrumentor
5959
ExceptionInstrumentor().instrument()
6060

61+
# Automatic exception handling for flask
62+
from flask import Flask, request
63+
from flask.signals import got_request_exception, appcontext_pushed
64+
import traceback
65+
66+
def _capture_exception(sender, exception, **extra):
67+
exc_type, exc_value, exc_traceback = sys.exc_info() # Get exception details
68+
if exc_type and exc_value and exc_traceback:
69+
record_exception(exc_type, exc_value, exc_traceback)
70+
else:
71+
print("Unable to capture exception details.")
72+
73+
def try_register_flask_handler(app: Flask):
74+
"""Registers the exception handler using Flask signals."""
75+
got_request_exception.connect(_capture_exception, app)
76+
print("✅ Flask error handler registered via signal.")
77+
78+
def _auto_register(sender, **extra):
79+
"""Automatically registers the handler when a Flask app context is pushed."""
80+
try_register_flask_handler(sender)
81+
82+
# Connect to Flask's appcontext_pushed to register automatically
83+
appcontext_pushed.connect(_auto_register)
84+
85+

pyproject.toml

Lines changed: 2 additions & 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.2rc4"
7+
version = "2.1.2rc5"
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" }]
@@ -21,6 +21,7 @@ keywords = [
2121
]
2222
dependencies =[
2323
"distro==1.9.0",
24+
"flask==2.3.2",
2425
"opentelemetry-api==1.27.0",
2526
"opentelemetry-exporter-otlp-proto-grpc==1.27.0",
2627
"opentelemetry-instrumentation==0.48b0",

0 commit comments

Comments
 (0)