Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(api): keep unhandled-exception 500s inside the middleware stack

Bingxi Zhao (Frank)57412238cd8c
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index dea9452b9..885bc7f81 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -244,23 +244,35 @@ app = FastAPI(
)
[email protected]_handler(Exception)
-async def unhandled_exception_handler(request: Request, exc: Exception):
- """Catch-all so 500s always return JSON, never Starlette's plain-text body."""
- logger.error(
- "Unhandled exception on %s %s: %s",
- request.method,
- request.url.path,
- exc,
- exc_info=True,
- )
- return JSONResponse(
- status_code=500,
- content={
- "detail": f"{type(exc).__name__}: {exc}",
- "type": type(exc).__name__,
- },
- )
+async def json_error_boundary(request: Request, call_next):
+ """Catch-all so 500s always return JSON, never Starlette's plain-text body.
+
+ Registered as a middleware rather than an ``@app.exception_handler``: a
+ handler for ``Exception`` is installed on Starlette's outermost
+ ``ServerErrorMiddleware``, so its response skips every middleware added
+ here — the 500 would carry no CORS headers (a cross-origin caller sees an
+ opaque CORS failure instead of this body) and would never reach the access
+ log below. Registered *before* ``CORSMiddleware``, this boundary sits
+ inside it, so the response travels back out through the normal stack.
+ """
+ try:
+ return await call_next(request)
+ except Exception as exc:
+ logger.error(
+ "Unhandled exception on %s %s: %s",
+ request.method,
+ request.url.path,
+ exc,
+ exc_info=True,
+ )
+ return JSONResponse(
+ status_code=500,
+ content={
+ "detail": f"{type(exc).__name__}: {exc}",
+ "type": type(exc).__name__,
+ },
+ )
# Access logging is funneled through this one middleware. uvicorn's own
diff --git a/tests/api/test_main_exception_handler.py b/tests/api/test_main_exception_handler.py
index 5e4e7287c..ef38637a4 100644
--- a/tests/api/test_main_exception_handler.py
+++ b/tests/api/test_main_exception_handler.py
@@ -3,15 +3,18 @@ from __future__ import annotations
from fastapi.testclient import TestClient
-def test_unhandled_exception_returns_json_error() -> None:
+def _client_with_failing_route() -> TestClient:
from deeptutor.api.main import app
@app.get("/api/v1/__test_unhandled_exception__")
def _raise_unhandled() -> None:
raise RuntimeError("intentional test failure")
- client = TestClient(app, raise_server_exceptions=False)
- response = client.get("/api/v1/__test_unhandled_exception__")
+ return TestClient(app, raise_server_exceptions=False)
+
+
+def test_unhandled_exception_returns_json_error() -> None:
+ response = _client_with_failing_route().get("/api/v1/__test_unhandled_exception__")
assert response.status_code == 500
assert response.headers["content-type"].startswith("application/json")
@@ -19,3 +22,26 @@ def test_unhandled_exception_returns_json_error() -> None:
"detail": "RuntimeError: intentional test failure",
"type": "RuntimeError",
}
+
+
+def test_unhandled_exception_response_carries_cors_headers() -> None:
+ """The 500 must travel back out through CORSMiddleware.
+
+ An ``@app.exception_handler(Exception)`` is installed on Starlette's
+ outermost ServerErrorMiddleware, so its response skips CORS entirely and a
+ cross-origin caller sees an opaque CORS failure rather than the JSON body
+ above — defeating the point of returning JSON at all. The boundary is a
+ middleware registered inside CORS precisely so this header survives.
+ """
+ client = _client_with_failing_route()
+ origin = "http://cross-origin.test"
+
+ ok = client.get("/api/v1/health", headers={"Origin": origin})
+ error = client.get("/api/v1/__test_unhandled_exception__", headers={"Origin": origin})
+
+ assert error.status_code == 500
+ # Whatever the CORS policy grants a normal response, it must also grant this one.
+ assert error.headers.get("access-control-allow-origin") == ok.headers.get(
+ "access-control-allow-origin"
+ )
+ assert error.headers.get("access-control-allow-origin") is not None