# Copyright (C) 2026 Mattia Zatelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """ Custom exceptions and error handlers """ import logging from typing import Any, Dict, Optional from fastapi import Request, status from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException logger = logging.getLogger(__name__) class BIMAPIException(Exception): """Base exception for BIM API""" def __init__( self, error_type: str, error_code: str, message: str, status_code: int = status.HTTP_400_BAD_REQUEST, details: Optional[Dict[str, Any]] = None, ): self.error_type = error_type self.error_code = error_code self.message = message self.status_code = status_code self.details = details or {} super().__init__(self.message) class AuthenticationError(BIMAPIException): """Authentication related errors""" def __init__(self, message: str = "Authentication failed", details: Optional[Dict] = None): super().__init__( error_type="authentication_error", error_code="auth_failed", message=message, status_code=status.HTTP_401_UNAUTHORIZED, details=details ) class AuthorizationError(BIMAPIException): """Authorization related errors""" def __init__(self, message: str = "Access denied", details: Optional[Dict] = None): super().__init__( error_type="authorization_error", error_code="access_denied", message=message, status_code=status.HTTP_403_FORBIDDEN, details=details ) class ProjectNotFoundError(BIMAPIException): """Project not found error""" def __init__(self, project_id: str): super().__init__( error_type="resource_error", error_code="project_not_found", message=f"Project {project_id} not found", status_code=status.HTTP_404_NOT_FOUND, details={"project_id": project_id} ) class ProjectNotReadyError(BIMAPIException): """Project not ready for operations""" def __init__(self, project_id: str, current_status: str): super().__init__( error_type="resource_error", error_code="project_not_ready", message=f"Project {project_id} is not ready (status: {current_status})", status_code=status.HTTP_400_BAD_REQUEST, details={"project_id": project_id, "status": current_status} ) class IFCProcessingError(BIMAPIException): """IFC file processing errors""" def __init__(self, message: str, details: Optional[Dict] = None): super().__init__( error_type="processing_error", error_code="ifc_processing_failed", message=message, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, details=details ) class FileUploadError(BIMAPIException): """File upload errors. Default status is 400 (Bad Request) — catches validation issues like bad filename, unsupported extension, or server-side problems surfacing through the upload endpoint. Pass status_code=413 explicitly for the genuine 'payload too large' case so monitoring can distinguish. """ def __init__( self, message: str, details: Optional[Dict] = None, status_code: int = status.HTTP_400_BAD_REQUEST, ): super().__init__( error_type="upload_error", error_code="upload_failed", message=message, status_code=status_code, details=details ) class QueryError(BIMAPIException): """Query processing errors""" def __init__(self, message: str, details: Optional[Dict] = None): super().__init__( error_type="query_error", error_code="query_failed", message=message, status_code=status.HTTP_400_BAD_REQUEST, details=details ) class ExternalServiceError(BIMAPIException): """External service errors (OpenAI, S3, etc.)""" def __init__(self, service: str, message: str, details: Optional[Dict] = None): super().__init__( error_type="external_service_error", error_code=f"{service}_error", message=f"{service} service error: {message}", status_code=status.HTTP_503_SERVICE_UNAVAILABLE, details=details ) class RateLimitError(BIMAPIException): """Rate limiting errors""" def __init__(self, message: str = "Rate limit exceeded", details: Optional[Dict] = None): super().__init__( error_type="rate_limit_error", error_code="rate_limit_exceeded", message=message, status_code=status.HTTP_429_TOO_MANY_REQUESTS, details=details ) async def bim_exception_handler(request: Request, exc: BIMAPIException) -> JSONResponse: """Handle BIM API exceptions""" request_id = getattr(request.state, "request_id", "unknown") logger.error( f"BIM API Error {request_id}: {exc.error_type}/{exc.error_code} - {exc.message}", extra={ "request_id": request_id, "error_type": exc.error_type, "error_code": exc.error_code, "status_code": exc.status_code, "details": exc.details, "path": request.url.path, "method": request.method, } ) return JSONResponse( status_code=exc.status_code, content={ "error": { "type": exc.error_type, "code": exc.error_code, "message": exc.message, "request_id": request_id, **exc.details } } ) async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse: """Handle validation errors""" request_id = getattr(request.state, "request_id", "unknown") logger.warning( f"Validation Error {request_id}: {exc.errors()}", extra={ "request_id": request_id, "errors": exc.errors(), "path": request.url.path, "method": request.method, } ) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={ "error": { "type": "validation_error", "code": "invalid_request", "message": "Request validation failed", "request_id": request_id, "validation_errors": exc.errors() } } ) async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: """Handle HTTP exceptions""" request_id = getattr(request.state, "request_id", "unknown") logger.warning( f"HTTP Error {request_id}: {exc.status_code} - {exc.detail}", extra={ "request_id": request_id, "status_code": exc.status_code, "detail": exc.detail, "path": request.url.path, "method": request.method, } ) return JSONResponse( status_code=exc.status_code, content={ "error": { "type": "http_error", "code": f"http_{exc.status_code}", "message": exc.detail, "request_id": request_id, } } ) async def general_exception_handler(request: Request, exc: Exception) -> JSONResponse: """Handle unexpected exceptions""" request_id = getattr(request.state, "request_id", "unknown") logger.exception( f"Unexpected Error {request_id}: {exc}", extra={ "request_id": request_id, "exception_type": type(exc).__name__, "path": request.url.path, "method": request.method, } ) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "error": { "type": "internal_error", "code": "unexpected_error", "message": "An unexpected error occurred", "request_id": request_id, } } )