from __future__ import annotations import logging from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from sqlalchemy.exc import SQLAlchemyError from app.core.api_errors import error_detail from app.features.access.errors import AccessUnauthorizedError from app.features.auth.errors import ( AuthError, CurrentPasswordIncorrectError, InvalidCredentialsError, InvalidEmailError, InvalidOrExpiredOtpError, InvalidPhoneNumberError, InvalidTokenError, UnauthorizedError, UserAlreadyExistsError, UserInactiveError, UserNotFoundError, WeakPasswordError, ) from app.features.content.errors import ( AmbiguousTemplateCodeError, ContentAttributeHierarchyError, ContentDefinitionSetError, ContentNotFoundError, ContentProjectionError, ContentReferenceResolutionError, InvalidPresentationContractError, InvalidSearchFieldError, InvalidSearchOperatorError, InvalidSearchValueError, InvalidSortFieldError, ModuleIdentityConflictError, ModuleNotFoundError, PresentationContractNotFoundError, PublishValidationError, RepositoryError, RequiredAttributeMissingError, TemplateNotCollectionError, TemplateNotFoundError, TemplateNotInModuleError, ) from app.features.search.errors import FacetNotFoundError, SearchFeatureError, SearchIndexError, SearchScopeError logger = logging.getLogger(__name__) def _response(*, status_code: int, code: str, message: str, context: dict[str, object] | None = None) -> JSONResponse: return JSONResponse(status_code=status_code, content={"detail": error_detail(code, message, context=context)}) async def access_unauthorized_handler(request: Request, exc: AccessUnauthorizedError) -> JSONResponse: return _response(status_code=status.HTTP_401_UNAUTHORIZED, code="AUTH_UNAUTHORIZED", message="Your session is missing, expired, or invalid.") async def auth_error_handler(request: Request, exc: AuthError) -> JSONResponse: if isinstance(exc, (UnauthorizedError, InvalidTokenError)): return _response(status_code=401, code="AUTH_UNAUTHORIZED", message="Your session is missing, expired, or invalid.") if isinstance(exc, UserInactiveError): return _response(status_code=403, code="AUTH_USER_INACTIVE", message=str(exc) or "This user account is inactive.") if isinstance(exc, UserNotFoundError): return _response(status_code=404, code="AUTH_USER_NOT_FOUND", message=str(exc) or "User was not found.") if isinstance(exc, (InvalidCredentialsError, InvalidEmailError, InvalidOrExpiredOtpError, InvalidPhoneNumberError, WeakPasswordError, UserAlreadyExistsError, CurrentPasswordIncorrectError)): return _response(status_code=400, code=type(exc).__name__.replace("Error", "").upper(), message=str(exc) or "Authentication request is invalid.") logger.error("Unhandled authentication domain error", exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="AUTH_OPERATION_FAILED", message="Authentication operation failed.") async def content_domain_error_handler(request: Request, exc: Exception) -> JSONResponse: if isinstance(exc, ContentNotFoundError): return _response(status_code=404, code="CONTENT_NOT_FOUND", message=str(exc) or "Content was not found.") if isinstance(exc, TemplateNotFoundError): return _response(status_code=404, code="TEMPLATE_NOT_FOUND", message=str(exc), context={"template_code": exc.template_code}) if isinstance(exc, ModuleNotFoundError): return _response(status_code=404, code="MODULE_NOT_FOUND", message=str(exc) or "Module was not found.") if isinstance(exc, PresentationContractNotFoundError): return _response(status_code=404, code="PRESENTATION_CONTRACT_NOT_FOUND", message=str(exc), context={"template_code": exc.template_code, "client_type": exc.client_type}) if isinstance(exc, (AmbiguousTemplateCodeError, ModuleIdentityConflictError, TemplateNotInModuleError, TemplateNotCollectionError)): context = {"template_code": exc.template_code, "matches": exc.matches} if isinstance(exc, AmbiguousTemplateCodeError) else None return _response(status_code=409, code=type(exc).__name__.replace("Error", "").upper(), message=str(exc), context=context) if isinstance(exc, (InvalidSearchFieldError, InvalidSearchOperatorError, InvalidSearchValueError, InvalidSortFieldError, ContentDefinitionSetError, RequiredAttributeMissingError, ContentAttributeHierarchyError, PublishValidationError, ContentReferenceResolutionError)): return _response(status_code=422, code=type(exc).__name__.replace("Error", "").upper(), message=str(exc) or "Content request is invalid.") if isinstance(exc, (ContentProjectionError, InvalidPresentationContractError, RepositoryError)): logger.error("Content operation failed", exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="CONTENT_OPERATION_FAILED", message="Unable to complete the content operation.") logger.error("Unhandled content domain error", exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="CONTENT_OPERATION_FAILED", message="Unable to complete the content operation.") async def search_domain_error_handler(request: Request, exc: SearchFeatureError) -> JSONResponse: if isinstance(exc, FacetNotFoundError): return _response(status_code=404, code="SEARCH_FACET_NOT_FOUND", message=str(exc) or "Search facet was not found.") if isinstance(exc, SearchScopeError): return _response(status_code=422, code="SEARCH_SCOPE_INVALID", message=str(exc) or "Search scope is invalid.") if isinstance(exc, SearchIndexError): logger.error("Search index operation failed", exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="SEARCH_INDEX_ERROR", message="Search is temporarily unavailable.") logger.error("Unhandled search domain error", exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="SEARCH_OPERATION_FAILED", message="Search is temporarily unavailable.") async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse: issues = [{"type": item.get("type"), "loc": list(item.get("loc", ())), "msg": item.get("msg")} for item in exc.errors()] return _response(status_code=422, code="REQUEST_VALIDATION_ERROR", message="The request contains invalid or missing values.", context={"issues": issues}) async def database_error_handler(request: Request, exc: SQLAlchemyError) -> JSONResponse: logger.error("Database operation failed: %s %s", request.method, request.url.path, exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="DATABASE_OPERATION_FAILED", message="The request could not be completed.") async def unexpected_error_handler(request: Request, exc: Exception) -> JSONResponse: logger.error("Unhandled API exception: %s %s", request.method, request.url.path, exc_info=(type(exc), exc, exc.__traceback__)) return _response(status_code=500, code="INTERNAL_SERVER_ERROR", message="An unexpected server error occurred.") def register_exception_handlers(app: FastAPI) -> None: app.add_exception_handler(AccessUnauthorizedError, access_unauthorized_handler) app.add_exception_handler(AuthError, auth_error_handler) for error_type in ( ContentNotFoundError, ContentDefinitionSetError, RequiredAttributeMissingError, ContentAttributeHierarchyError, PublishValidationError, RepositoryError, TemplateNotFoundError, AmbiguousTemplateCodeError, PresentationContractNotFoundError, InvalidPresentationContractError, ModuleNotFoundError, ModuleIdentityConflictError, TemplateNotInModuleError, TemplateNotCollectionError, InvalidSearchFieldError, InvalidSearchOperatorError, InvalidSearchValueError, InvalidSortFieldError, ContentProjectionError, ContentReferenceResolutionError, ): app.add_exception_handler(error_type, content_domain_error_handler) app.add_exception_handler(SearchFeatureError, search_domain_error_handler) app.add_exception_handler(RequestValidationError, validation_error_handler) app.add_exception_handler(SQLAlchemyError, database_error_handler) app.add_exception_handler(Exception, unexpected_error_handler)