From 3996022a6c2e6023ceb88d9213ee1589680e5301 Mon Sep 17 00:00:00 2001 From: Itamar Shefi Date: Wed, 17 Apr 2024 17:42:31 +0300 Subject: [PATCH] Nicer user errors (first step) --- app.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app.py b/app.py index 53e2849..400c705 100644 --- a/app.py +++ b/app.py @@ -17,6 +17,7 @@ from fastapi.staticfiles import StaticFiles from common import config +from common.error import HSError from common.session import get_model from common.session import get_mongo from common.session import get_redis @@ -130,6 +131,16 @@ async def get_user( return await call_next(request) +@app.middleware("http") +async def catch_known_errors( + request: Request, call_next: Callable[[Request], Awaitable[Response]] +) -> Response: + try: + return await call_next(request) + except HSError as e: + return JSONResponse(content=str(e), status_code=status.HTTP_400_BAD_REQUEST) + + @app.get("/health") async def health() -> dict[str, str]: return {"message": "Healthy!"}