Skip to content

Commit 4e4e93a

Browse files
Juntao Yuanclaude
andcommitted
Add global exception handler with traceback
Returns detailed error info including exception type and traceback to help diagnose 500 errors in production. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 5ba3f47 commit 4e4e93a

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

main.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,21 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
3232
)
3333

3434

35+
@app.exception_handler(Exception)
36+
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
37+
"""Catch all unhandled exceptions and return a JSON error response."""
38+
import traceback
39+
40+
return JSONResponse(
41+
status_code=500,
42+
content={
43+
"error": str(exc),
44+
"type": type(exc).__name__,
45+
"traceback": traceback.format_exc(),
46+
},
47+
)
48+
49+
3550
@app.get("/")
3651
async def root() -> dict[str, str]:
3752
"""Root endpoint with service info."""

0 commit comments

Comments
 (0)