Spaces:
Runtime error
Runtime error
File size: 9,032 Bytes
e6be672 30ccb8a e6be672 30ccb8a e6be672 30ccb8a e6be672 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | # 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 <https://www.gnu.org/licenses/>.
"""
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,
}
}
) |