Skip to content

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

fix(api): return JSON for unhandled exceptions (#928)

evan188199-techa8d41bd4fa38
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index a8a17bc28..dea9452b9 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -2,8 +2,9 @@ from contextlib import asynccontextmanager
import logging
import sys
-from fastapi import Depends, FastAPI
+from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import JSONResponse
from deeptutor.logging import configure_logging
from deeptutor.services.config import (
@@ -242,6 +243,26 @@ app = FastAPI(
redirect_slashes=False,
)
+
[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__,
+ },
+ )
+
+
# Access logging is funneled through this one middleware. uvicorn's own
# per-request access log is disabled on every launch path (run_server.py via
# access_log=False; the launcher and Docker via `--no-access-log`), so routine
diff --git a/tests/api/test_main_exception_handler.py b/tests/api/test_main_exception_handler.py
new file mode 100644
index 000000000..5e4e7287c
--- /dev/null
+++ b/tests/api/test_main_exception_handler.py
@@ -0,0 +1,21 @@
+from __future__ import annotations
+
+from fastapi.testclient import TestClient
+
+
+def test_unhandled_exception_returns_json_error() -> None:
+ 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__")
+
+ assert response.status_code == 500
+ assert response.headers["content-type"].startswith("application/json")
+ assert response.json() == {
+ "detail": "RuntimeError: intentional test failure",
+ "type": "RuntimeError",
+ }