Add global exception handler — no more bare 500s
Browse files- backend/api/main.py +11 -0
backend/api/main.py
CHANGED
|
@@ -14,6 +14,7 @@ from pathlib import Path
|
|
| 14 |
|
| 15 |
from fastapi import FastAPI, Request, Response
|
| 16 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 17 |
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 18 |
from slowapi.errors import RateLimitExceeded
|
| 19 |
from slowapi.util import get_remote_address
|
|
@@ -110,6 +111,16 @@ app.state.limiter = limiter
|
|
| 110 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 111 |
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
# -- Request logging --------------------------------------------------------
|
| 114 |
|
| 115 |
@app.middleware("http")
|
|
|
|
| 14 |
|
| 15 |
from fastapi import FastAPI, Request, Response
|
| 16 |
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
+
from fastapi.responses import JSONResponse
|
| 18 |
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 19 |
from slowapi.errors import RateLimitExceeded
|
| 20 |
from slowapi.util import get_remote_address
|
|
|
|
| 111 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 112 |
|
| 113 |
|
| 114 |
+
@app.exception_handler(Exception)
|
| 115 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
| 116 |
+
"""Catch-all: log unhandled exceptions and return structured JSON instead of bare 500."""
|
| 117 |
+
log.error("Unhandled exception on %s %s: %s", request.method, request.url.path, exc, exc_info=True)
|
| 118 |
+
return JSONResponse(
|
| 119 |
+
status_code=500,
|
| 120 |
+
content={"detail": f"Internal server error: {type(exc).__name__}: {exc}"},
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
# -- Request logging --------------------------------------------------------
|
| 125 |
|
| 126 |
@app.middleware("http")
|