Skip to content

Commit 102174a

Browse files
committed
✨ [feat][backend] Improve error logging
1 parent 70fd162 commit 102174a

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

backend/kayman/main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
SPAStaticFiles,
1212
custom_generate_unique_id,
1313
lifespan,
14+
setup_exception_handlers,
1415
setup_logger,
1516
)
1617

@@ -54,3 +55,6 @@
5455

5556
# Override the OpenAPI generation to customize operationId
5657
override_openapi(app)
58+
59+
# Log unhandled exceptions through loguru and return a clean 500
60+
setup_exception_handlers(app)

backend/kayman/util.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from zoneinfo import ZoneInfo
99

1010
import simplejson
11-
from fastapi import FastAPI
11+
from fastapi import FastAPI, Request
1212
from fastapi.responses import JSONResponse
1313
from fastapi.routing import APIRoute
1414
from fastapi.staticfiles import StaticFiles
@@ -85,6 +85,21 @@ def custom_generate_unique_id(route: APIRoute) -> str:
8585
return f"{route.tags[0]}-{route.name}"
8686

8787

88+
def setup_exception_handlers(app: FastAPI) -> None:
89+
@app.exception_handler(Exception)
90+
async def unhandled_exception_handler(request: Request, exc: Exception) -> Response:
91+
route = request.scope.get("route")
92+
logger.bind(
93+
method=request.method,
94+
path=request.url.path,
95+
route=getattr(route, "path", None),
96+
client_host=request.client.host if request.client else None,
97+
).opt(exception=exc).error("Unhandled exception")
98+
return KustomJSONResponse(
99+
status_code=500, content={"detail": "Internal Server Error"}
100+
)
101+
102+
88103
def handle_special_types(obj: Any) -> Any:
89104
print(f"handled type: {type(obj)}, {obj=}")
90105
if isinstance(obj, BaseModel):

0 commit comments

Comments
 (0)