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

A catch-all handler so 500s carry a JSON body instead of Starlette's plain-text default.
This commit is contained in:
evan188199-tech
2026-08-19 23:36:18 +08:00
committed by GitHub
parent 5afb2547da
commit a8d41bd4fa
2 changed files with 43 additions and 1 deletions

View File

@@ -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,
)
@app.exception_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

View File

@@ -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",
}