mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 16:39:22 +08:00
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:
@@ -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
|
||||
|
||||
21
tests/api/test_main_exception_handler.py
Normal file
21
tests/api/test_main_exception_handler.py
Normal 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",
|
||||
}
|
||||
Reference in New Issue
Block a user