Skip to content

Commit

Permalink
Introduces a kwik_exception_handler to format and handle custom appli…
Browse files Browse the repository at this point in the history
…cation exceptions derived from KwikException
  • Loading branch information
dmezzogori committed May 29, 2023
1 parent 7f09d48 commit 4bbed32
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
3 changes: 3 additions & 0 deletions kwik/applications/kwik.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from fastapi import FastAPI
from kwik import settings
from kwik.api.endpoints.docs import get_swagger_ui_html
from kwik.exceptions import KwikException
from kwik.middlewares import DBSessionMiddleware, RequestContextMiddleware
from kwik.websocket.deps import broadcast
from starlette.middleware.cors import CORSMiddleware
Expand Down Expand Up @@ -62,6 +63,8 @@ def __init__(self, api_router: APIRouter) -> None:

self._app.include_router(api_router, prefix=settings.API_V1_STR)

self._app.exception_handler(KwikException)(kwik.exceptions.handler.kwik_exception_handler)

@self._app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
Expand Down
7 changes: 5 additions & 2 deletions kwik/exceptions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from .base import KwikException, DuplicatedEntity, Forbidden, NotFound
from __future__ import annotations

from .base import DuplicatedEntity, Forbidden, KwikException, NotFound
from .exporters import ExporterLimitExceeded
from .users import UserInactive, IncorrectCredentials, UserNotFound
from .handler import kwik_exception_handler
from .users import IncorrectCredentials, UserInactive, UserNotFound
12 changes: 12 additions & 0 deletions kwik/exceptions/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from __future__ import annotations

from fastapi import Request
from kwik.exceptions import KwikException
from starlette.responses import JSONResponse


async def kwik_exception_handler(request: Request, exc: KwikException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)

0 comments on commit 4bbed32

Please sign in to comment.