service_man/api/app_builder/error_handlers.py

52 lines
1.6 KiB
Python
Raw Normal View History

2024-04-08 00:31:15 +03:00
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from api.domain.error import DomainValidationError
from api.domain.user.error import (UserAlreadyExistsError,
UserInvalidCredentialsError,
UserIsNotAuthorizedError)
async def validation_error_exc_handler(
request: Request, exc: DomainValidationError
) -> JSONResponse:
return JSONResponse(status_code=400, content={"detail": exc.message})
async def user_authentication_error_exc_handler(
request: Request, exc: UserIsNotAuthorizedError
) -> JSONResponse:
return JSONResponse(
status_code=401,
content={"detail": exc.message},
headers={"WWW-Authenticate": "Bearer"},
)
async def user_already_exist_error_exc_handler(
request: Request, exc: UserAlreadyExistsError
) -> JSONResponse:
return JSONResponse(status_code=409, content={"detail": exc.message})
async def user_invalid_credentials_error_exc_handler(
request: Request, exc: UserInvalidCredentialsError
) -> JSONResponse:
return JSONResponse(status_code=401, content={"detail": exc.message})
def init_exc_handlers(app: FastAPI) -> None:
app.add_exception_handler(
DomainValidationError,
validation_error_exc_handler,
)
app.add_exception_handler(
UserIsNotAuthorizedError, user_authentication_error_exc_handler
)
app.add_exception_handler(
UserAlreadyExistsError, user_already_exist_error_exc_handler
)
app.add_exception_handler(
UserInvalidCredentialsError, user_invalid_credentials_error_exc_handler
)