2024-04-08 00:31:15 +03:00
|
|
|
from fastapi import FastAPI, Request
|
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
|
|
|
from api.domain.error import DomainValidationError
|
2024-04-23 12:08:56 +03:00
|
|
|
from api.domain.user.error import (
|
|
|
|
UserAlreadyExistsError,
|
|
|
|
UserInvalidCredentialsError,
|
|
|
|
UserIsNotAuthorizedError,
|
|
|
|
)
|
2024-04-23 11:10:17 +03:00
|
|
|
from api.infrastructure.persistence.error import TransactionContextManagerError
|
2024-04-08 00:31:15 +03:00
|
|
|
|
|
|
|
|
2024-04-23 12:08:56 +03:00
|
|
|
async def transaction_error_exec_handler(request: Request, exc: TransactionContextManagerError) -> JSONResponse:
|
2024-04-23 11:10:17 +03:00
|
|
|
return JSONResponse(status_code=400, content={"detail": exc.message})
|
|
|
|
|
|
|
|
|
2024-04-23 12:08:56 +03:00
|
|
|
async def validation_error_exc_handler(request: Request, exc: DomainValidationError) -> JSONResponse:
|
2024-04-08 00:31:15 +03:00
|
|
|
return JSONResponse(status_code=400, content={"detail": exc.message})
|
|
|
|
|
|
|
|
|
2024-04-23 12:08:56 +03:00
|
|
|
async def user_authentication_error_exc_handler(request: Request, exc: UserIsNotAuthorizedError) -> JSONResponse:
|
2024-04-08 00:31:15 +03:00
|
|
|
return JSONResponse(
|
|
|
|
status_code=401,
|
|
|
|
content={"detail": exc.message},
|
|
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-04-23 12:08:56 +03:00
|
|
|
async def user_already_exist_error_exc_handler(request: Request, exc: UserAlreadyExistsError) -> JSONResponse:
|
2024-04-08 00:31:15 +03:00
|
|
|
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,
|
|
|
|
)
|
2024-04-23 12:08:56 +03:00
|
|
|
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)
|
2024-04-23 11:10:17 +03:00
|
|
|
|
2024-04-23 12:08:56 +03:00
|
|
|
app.add_exception_handler(TransactionContextManagerError, transaction_error_exec_handler)
|